Validation With Yup

Paul Alles
4 min readSep 25, 2023

--

Yup is a library for validating user input in JavaScript that follows a structured and declarative approach. It provides a user-friendly syntax for defining validation schemas, and a comprehensive set of validation rules to ensure that your data is reliable and accurate.

With Yup, you can easily validate various types of data, from simple values like strings, numbers, and dates, to more complex data structures like nested objects and arrays. Additionally, you can tailor validation rules and error messages to match your specific requirements.

One of the primary advantages of using Yup is that it plays well with other JavaScript libraries and frameworks, like Formik and React, which makes it a popular choice for front-end development.

Some of the features of yup

  • Schema-based validation: Yup allows you to define a schema for your data, and validate that data against the schema. The schema defines the structure of your data, as well as the validation rules for each field.
  • Simple and intuitive syntax: Yup provides a clean and easy-to-understand syntax for defining validation rules. The syntax is similar to that of chaining methods, so it’s easy to read and write.
  • Rich set of validation rules: Yup provides a wide range of built-in validation rules, such as required fields, string length limits, email validation, and more. You can also define custom validation rules to suit your specific needs.
  • Custom error messages: Yup allows you to define custom error messages for your validation rules, so you can provide more informative feedback to your users.
  • Integration with other libraries: Yup integrates well with other JavaScript libraries and frameworks, such as React and Formik, making it a popular choice for front-end developers.

Javascript Validation Example:

Install Yup Package: npm install yup

First of all to use Yup validation, you first need to create a Yup schema object. This object defines the expected structure and validation rules for your form data. Then we can trigger validation rules whereever you want.

Here is a basic yup validation in Javascript. We can use this kind of validation for backend.

import * as yup from 'yup';

// schema for yup validation
const schema = yup.object().shape({
name: yup.string().required(),
email: yup.string().email().required(),
age: yup.number().positive().integer().required(),
password: yup.string().required().min(6),
confirmPassword: yup.string().oneOf([yup.ref('password'), null], 'Passwords must match'),
});

// data object that need to be validated
const data = {
name: 'John Doe',
email: 'john.doe@example.com',
age: 30,
password: 'password123',
confirmPassword: 'password123',
};

// trigger validation rule
schema.validate(data)
.then(valid => console.log(valid))
.catch(error => console.log(error));

Yup validation can be used with or without a form library. If you are using a form library such as Formik, you can pass the Yup schema object to the library’s validationSchema prop. This will allow the library to automatically handle validation for you.

Example validation with Formik library
In this example, Formik will automatically handle validation for the form fields. If the user enters invalid data, Formik will display error messages next to the relevant fields.

import * as Yup from 'yup';
import Formik from 'formik';

const schema = Yup.object().shape({
name: Yup.string().required(),
email: Yup.string().email().required(),
});

const MyForm = () => {
const [formData, setFormData] = useState({
name: '',
email: '',
});

const handleChange = (event) => {
const { name, value } = event.target;

setFormData({
...formData,
[name]: value,
});
};

const handleSubmit = async (event) => {
event.preventDefault();

const errors = await schema.validate(formData);

if (errors) {
// Handle validation errors
} else {
// Submit the form data to your backend
}
};

return (
<Formik
initialValues={formData}
validationSchema={schema}
onSubmit={handleSubmit}
>
{({ values, errors, handleChange, handleSubmit }) => (
<form onSubmit={handleSubmit}>
<input
type="text"
name="name"
value={values.name}
onChange={handleChange}
placeholder="Enter your name"
/>
<input
type="email"
name="email"
value={values.email}
onChange={handleChange}
placeholder="Enter your email"
/>
<button type="submit">Submit</button>
</form>
)}
</Formik>
);
};

Example validation without form library.
In this example, we first create a Yup schema object to define the expected structure and validation rules for our form data. Then, we create a validateFormData() function to validate the form data using the Yup schema. The validateFormData() function returns an error object if the data is invalid, or undefined if the data is valid.

import * as Yup from 'yup';
// schema
const schema = Yup.object().shape({
name: Yup.string().required(),
email: Yup.string().email().required(),
});

// method to trigger validation and return the error message
const validateFormData = async (formData) => {
const errors = await schema.validate(formData);

if (errors) {
return errors;
} else {
return undefined;
}
};

Html form that need to be validated. form id(“my-form”) is used to refer this form for validation check.

<form id="my-form">
<input type="text" name="name" placeholder="Enter your name">
<input type="email" name="email" placeholder="Enter your email">
<button type="submit">Submit</button>
</form>

In this example, we listen for the submit event on the form. When the form is submitted, we call the validateFormData() function to validate the form data. If any errors are found, we handle them accordingly. Otherwise, we know that the form data is valid and we can submit it to our backend.

const form = document.querySelector('#my-form');

form.addEventListener('submit', async (event) => {
event.preventDefault();

const formData = new FormData(form);

const errors = await validateFormData(formData);

if (errors) {
// Handle validation errors
} else {
// The form data is valid
}
});

Yup validation is a powerful and flexible tool for validating form data in JavaScript applications. It is easy to use and provides a wide range of validation features.

--

--