admin管理员组

文章数量:1317123

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
Add a ment  | 

2 Answers 2

Reset to default 3

Shorted:

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.

本文标签: javascriptYup validationcheck if value doesn39t match other fieldStack Overflow