Yup Validator 1.0

Yup Validator 1.0

Yup is a schema validator and used with many popular forms package, like formik and react-final-form...

What is Yup?

Yup is a javascript schema validator using which we can validate form fields. Let's say that we have a form with fields shown below in the form of a JSON object.

const values = {
  firstname: "Nikhil",
  lastname: "Gupta",
  email: "xyz@provider.com",
  password: "Test@123",
  confirmPassword: "Test@123",
};

Now, we need to ensure that the user fills out each information correctly, as all the values of the field should be valid respective to their property. So, what can be the validations?

  • firstname | lastname: The user should enter a string

  • email: user should provide a valid email address

  • password | confirmPassword: The user should set the password in the form that it must contain 1 numeric character, 1 uppercase, 1 lowercase and 1 special character, also both the field should match and the minimum number of characters should be 8.

Yup Object

Now, let's create a yup schema validator for the values object, which we defined above.

import * as yup from 'yup'

const schema = yup.object().shape({
    firstName: yup.string().required("First Name is required."),
    lastName: yup.string().required("Last Name is required."),
    email: yup.string().email().required("Email is required."),
    password: yup
        .string()
        .required("Password is required")
        .matches(
            /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[\^$*.\[\]{}\(\)?\-!@#%&\/,><\’:;|_~`])\S{8,99}$/,
            "Password requirement not satisfied"
        ),
    confirmPassword: yup
        .string()
        .oneOf([yup.ref("password"), null], "Passwords must match")
        .required("Password confirmation is required."),
});

In the above schema, firstname, lastname and email are pretty simple, but let me explain the password part.

So, in the yup, there is a property of matches inside which we can pass either a value or a regex to get matched, along with the string, which will print that if the user fails to satisfy that criterion.

confirm password and password should be an exact match, so we can get the value of the password field using reference using the property name, i.e, yup.ref("password"), and the rest is self-explanatory.

This is just a glimpse of the Yup schema validator, there is a lot more, we can validate everything, will soon come up with a practical tutorial.

For now, explore more about yup at npmjs.com/package/yup