Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - Yup Validation With Multiple Condition based on other field value

I have to validate the 'description' field when 'gender' field value is others or female but when it is male no validation required for the 'description' field.

First I want to show this code and this is valid and working:

description: Yup.string().when(['gender'], {
 is: (gender) => gender=== 'others',
 then: Yup.string().required('Description is Required')
})

But Now I have to use multiple conditions like this:

description: Yup.string().when(['gender'], {
 is: (gender) => gender=== 'others' || 'female' ,
 then: Yup.string().required('Description is Required')
})

But It's not working. Please Give me a solution. Thanks in advance...


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

1 Answer

0 votes
by (71.8m points)

Equality operation is evaluated first.

is: (gender) => gender === 'others' || 'female' ,   // Not good

becomes:

is: (gender) => (Boolean) || 'female',

where if <Boolean> is true you'll get true as result,
and if <Boolean> is false you'll get "female" as result.

SOLUTION:
Instead, use /^(others|female)$/.test(gender)
or ['others','female'].includes(gender) as suggested by @evolution

is: (gender) => /^(others|female)$/.test(gender) ,

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test

or if you want to make it long and explicit:

is: (gender) => gender === "others" || gender === "female" ,

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...