Reputation: 421
I'm trying to validate a number field that is optional, and therefore allowed to be empty. If there is a value in the field, it must be a positive number.
const schema = yup.object().shape({
gpa: yup.number()
.when('gpa', {
is: (value) => value?.length > 0,
then: yup.number().positive(numberPositiveMessage).typeError(numberMessage),
otherwise: yup.number().notRequired().nullable(true).transform(value => (isNaN(value) ? undefined : value))
},
[
['gpa', 'gpa'],
]
);
It allows the rest of the form to validate when the field is empty, and when there is a positive number in there, but if I enter a negative number or a string it does not return any errors like it should.
Upvotes: 12
Views: 12956
Reputation: 1418
For the next person that winds up here trying to do the same thing, this works for positive numbers that can be 0, null, undefined or an empty string but not any other string or a negative number:
const schema = yup.object().shape({
gpa: yup.number()
.typeError("GPA must be a number")
.nullable()
.moreThan(0, "Floor area cannot be negative")
.transform((_, val) => (val !== "" ? Number(val) : null)),
}
);
The Number cast triggers a type error on a string that will give you the error defined in .typeError() and using .moreThan() instead of .positive() allows you to have zero (switch to .positive() if you don't want to allow 0).
Upvotes: 12