DEV Community

Cover image for Advance Yup Validations
Kush Bhandari
Kush Bhandari

Posted on

Advance Yup Validations

Yup is a common library used for validation purpose of the form in react with react-hook-form or formik.

1) Using test
Suppose you are writing a validation and you want to check if user input is valid. so you can write test condition for that.
for example: Age field should have value greater than 18.
age: yup.string().test({message:'Please enter a valid age',test: (value) =>{return value>18}}}).

2) Using when:
Support nationality document is only required when nationality is others.
fileInput: yup.string().when("nationality", {
is: "Others",
then: (schema) =>
schema.required("Nationality document is required"),
});

3) Using function
If premium is greater than 1 lakh than pan card field is required.
panNo: yup
.string()
.test("PanCardRequired", "PAN Number is required", function (value) {
if (premiumValue > 100000) {
if (value !== undefined || value === "") {
return value ? true : false;
}
}

        return true;
      }),
Enter fullscreen mode Exit fullscreen mode

Top comments (0)