Reputation: 1015
How to implement the condition like value of 1 field should always be greater than the value of another field.
here's my schema
value: Yup.number().required(''),
value2: Yup.number().when('value',{
is: (val) => something here
then: Yup.number().required('Required').positive('value should be positive'),
otherwise: Yup.number()
})
I want to check for value2 to always be > value. How to access value2's value in the when condition?
Upvotes: 1
Views: 11728
Reputation: 1
I am validating same fields for email and mobile no so user can validate both is same field.
username: yup
.string().when({
is : value =>isNaN(value),
then: yup.string().required('email/mobileno is required') .matches( Regex.EMAIL_REGX,
'Invalid email',
),
otherwise: yup.string()
.matches(Regex.PHONENO_REGX, StringUtils.phoneNo)
}),
Upvotes: -1
Reputation: 21
Try this if you want to compare more than condition between two fields
import * as Yup from 'yup';
value: Yup.number().required(''),
value2: Yup.number().required()
.moreThan(
Yup.ref('value'),
'Should be more than value2'
)
Upvotes: 2
Reputation: 2444
I'm not sure it's the right way to do it, but I'm using test.
Like this:
yourField: Yup.string().test('should-be-greather-than-yourField2', 'Should be greather than yourfield 2', function(value) {
const otherFieldValue = this.parent.yourField2
if (!otherFieldValue) {
return true;
}
return value > otherFieldValue;
})
Upvotes: 5