Hi I am trying to find a way to pare 2 fields and validate only if they are not equal.
This is the only idea I was able to e up with but it doesn't work:
yup
.number()
.required()
.notOneOf(
[FormField.houseHoldMembers as any],
'error message',
),
Hi I am trying to find a way to pare 2 fields and validate only if they are not equal.
This is the only idea I was able to e up with but it doesn't work:
yup
.number()
.required()
.notOneOf(
[FormField.houseHoldMembers as any],
'error message',
),
Share
Improve this question
asked Sep 23, 2022 at 9:08
RomanRoman
731 silver badge5 bronze badges
2 Answers
Reset to default 3Shorted:
const schema = yup.object({
field1: yup.number().required(),
field2: yup
.number()
.required()
.notOneOf([yup.ref('field1'), null], 'The two values should not be equal'),
});
You can pare the two values and validate only if they are not equal like this:
const mySchema = yup.object({
text1: yup.number().required(),
text2: yup
.number()
.required()
.when(["text1"], (text1, schema) => {
console.log(schema);
return schema.notOneOf([text1], "the two values should not be equal");
})
});
You can take a look at this sandbox for a live working example of this solution.