DEV Community

Cover image for Using yup to build schema with value parsing and validation.
Bello Shehu
Bello Shehu

Posted on

Using yup to build schema with value parsing and validation.

Validation is a very important aspect of application development, in which user input data is tested against a predetermined format or value to ensure accuracy and quality of data entered into the application.

There are a bunch of tools used for validating user input both in the frontend and backend applications. Among such tools is yup; a very popular schema builder with value parsing and validation capabilities.

Below are examples of how to use yup to build user signup schema with validation in JavaScript.

First off, we need to install yup and import it into the file we want to use it:

npm i yup

import * as yup from "yup";
Enter fullscreen mode Exit fullscreen mode

1. Building basic user signup schema
This simple yup schema is for user signup containing user's email, password, and username. All fields are required:

const basic_signup_schema = yup.object({
  email: yup.string().email().required("Email required"),
  password: yup.string().required("Password required"),
  username: yup.string().required("Username required"),
});
Enter fullscreen mode Exit fullscreen mode

The .string method validates email ID to string. Whereas, the .email validates any email ID entered.

If this schema is used with a form library such as Formik, the individual form fields will be validated accordingly. Hence, the form will not be submitted if at least one of the fields is empty.

2. Adding more validation to signup schema
To make the user's password stronger and hence difficult for a hacker to guess, it must contain digits, upper and lower case, special characters and be at least 8 characters long.

const signup_schema = yup.object({
  email: yup.string().email("Invalid email").required("Email required"),
  password: yup
    .string()
    .min(8, "Must be 8 characters long")
    .required("Password required")
    .matches(/[a-z]+/, "Must contain lowercase character")
    .matches(/[A-Z]+/, "Must contain uppercase character")
    .matches(
      /[_@$!%*#?&]+/,
      "Must contain at least one special character among $ ! % * # ? & _ @ "
    )
    .matches(/\d+/, "Must contain digit"),
  username: yup.string().required("Username required"),
});
Enter fullscreen mode Exit fullscreen mode

Conclusion
Data validation is used to ensure security, and integrity of data stored in application's database. Hence, using a library such as yup is an effective and easier way you can ensure that the user enters correct data into your application.

For suggestions, correction and questions, kindly make a comment in the comment section.

Thanks for reading!

Top comments (0)