I’m trying to compare 2 number inputs with yup
validation.
One of the names is number1
and the other is number2
.
number2 must be greater than or equal to number1 and number1 must be less than or equal to number2.
If I enter a 5 to number1
and then I enter 4 to number 1 I am getting a yup
validation error message as number2
must be greater than or equal to 5". It is okay.
But if I change number1
to 3 the error message still exists. Whereas in this case, number1
is less than number2
.
How can I manage these two input error messages dynamically with yup validation?
My validation schema:
validationSchema: {
number1: yup
.number()
.required()
.when('number2', (number2: any, schema: any) => {
if (number2) {
return schema.max(number2);
}
}),
number2: yup
.number()
.required()
.when('number1', (number1: any, schema: any) => {
if (number1) {
return schema.min(number1);
}
}),
},
The error message I get
inputs with error message
I tried yup methods with using when or without when I also used ReactJs and React hook form.
I’m expecting that when I get an error message like the above if I change the other input all error messages disappear.
2
Answers
Solution
The problem has been solved but as I said above I'm using react-hook-form and the problem was related to react-hook-form. I had to add deps to Controller of these two inputs.
Github url that I found the solution: https://github.com/orgs/react-hook-form/discussions/8633
Resolved this issue using the below validation schema:
Note: Make sure you have the latest version of Yup installed to ensure the test method works correctly.