Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
145 views
in Technique[技术] by (71.8m points)

reactjs - React form validation for multiple field

I am new to React. I have a very simple form which contains employer address details. I would like to validate if any of the fields got value, then check if length is <=10 and if not exists the it is fine. There are no mandatory validation and only length valiation if exists.

currently doing like below:

  const isValid=
    employer.address == null ||
    (employer.address != null &&
      (employer.address.building?.length <= 2) &&
      employer.address.street?.length <= 2 &&
      employer.address.county?.length <= 2 &&
      employer.address.city?.length <= 2 &&
      employer.address.postcode?.length <= 2);

Is there a better way to test to check validation if it contains value and ignore if not.

question from:https://stackoverflow.com/questions/65887534/react-form-validation-for-multiple-field

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

it is neither bad nor the best way

with current code you can do a bit clean Up to make it look nicer
you can assign a const to employer.address so no need to repeat it

const emp = employer.address
const isValid=
    !emp||
    (emp&&
      (emp.building?) &&
      emp.street?&&
      emp.county?&&
      emp.city? &&
      emp.postcode?);

in the example above validation works if data is '' but if it has anything inside it ('s') validation would not be called
i think it should work same way

also there are some packages that provide you validation

redux form https://redux-form.com/8.3.0/

yup https://www.npmjs.com/package/yup


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...