I'm using yup and React Form Hook to handle my form. My form consists of an array of objects that contains text fields of type number. One of the validations is the lower limit of the array in position 1 must be the equal upper limit of position 0 plus 1. array[1].LowerLimit = array[0].UpperLimit + 1. I did it using yup.test and it works well.
This is my schema.
Array: yup.array().of(
yup.object().shape({
LowerLimit: yup.number()
.positive()
.typeError('Lower Limit must be a number')
.min(0, 'Lower Limit must be greater or equal to 0')
.max(99998, 'Lower Limit must be lower or equal to 99998')
.required(),
UpperLimit: yup.number()
.positive()
.typeError('Upper Limit must be a number')
.min(0, 'Upper Limit must be greater or equal to 0')
.max(99999, 'Upper Limit must be lower or equal to 99999')
.moreThan(yup.ref('LowerLimit'), 'Lower limit must be lower than UpperLimit')
.required(),
})
)
and this is my yup.test() function.
.test("valid-nextLowerlimit-mustBe-beforeUpperLimit-plus1", (array) => {
for (let index = 1; index < array.length; index++) {
const item = array[index];
const isLowerLimitEqualBeforeUpperLimitPlusOne = item.LowerLimit
=== array[index - 1].UpperLimit + 1;
if (!isLowerLimitEqualBeforeUpperLimitPlusOne) {
return this.createError(
{
message: `The Lower limit of Rule ${index + 1} must be ${array[index - 1].UpperLimit + 1}`
});
}
}
return true;
})
When I click Submit button, my form validated it (lower limit must be before upper limit plus one) but if I'd like to validate the lower limit text field must be a number it doesn't happen only check my yup.test custom validations.
The thing is, I have other tests, and these tests flap the object.shape validations like .min or max. Exists a way to use these tests without flapping objects. shape validations?
Example of error in console
Object { message: "The Lower limit of Rule 2 must be 31", type: "valid-nextLowerlimit-mustBe-beforeUpperLimit-plus1", ref: undefined }