Skip to main content

Mastering Form Validation with Yup

· 4 min read
Parth Maheta

Yup is a JavaScript schema validation library that simplifies the process of validating form data in web applications. In this comprehensive guide, we'll explore the fundamental concepts, key features, and practical examples to help you master Yup for effective form validation.

1. Introduction to Yup

1.1 What is Yup?

Yup is a declarative schema validation library that allows you to define a schema for your data and validate it against that schema. It is particularly useful for validating form inputs, ensuring that the data meets specified requirements.

1.2 Key Features

  • Declarative Schema: Define validation rules using a schema.
  • Chaining API: Chain methods for concise and expressive validation rules.
  • Asynchronous Validation: Support for asynchronous validation tasks.
  • Locale Support: Localize validation error messages.

2. Getting Started with Yup

2.1 Installation

Install Yup in your project using npm or yarn:

npm install yup

2.2 Importing Yup

Import Yup into your JavaScript file:

import * as yup from 'yup';

3. Defining Validation Schema

3.1 Basic Schema Definition

Define a simple schema for a form with Yup:

const schema = yup.object().shape({
username: yup.string().required(),
email: yup.string().email().required(),
age: yup.number().positive().integer().required(),
});

This schema enforces that the username and email are strings and required, while age must be a positive integer.

3.2 Validation Methods

Explore common validation methods like string(), number(), required(), email(), and more.

4. Performing Validation

4.1 Validating Sync and Async Data

Validate data synchronously:

const data = { username: 'John', email: '[email protected]', age: 25 };

schema.validateSync(data);

For asynchronous validation, use validate:

schema.validate(data)
.then(valid => console.log(valid))
.catch(err => console.error(err));

5. Handling Validation Errors

5.1 Error Messages

Customize error messages for each validation rule:

const customSchema = yup.object().shape({
username: yup.string().required('Username is required'),
email: yup.string().email('Invalid email').required('Email is required'),
age: yup.number().positive('Age must be positive').integer('Age must be an integer').required('Age is required'),
});

5.2 Error Objects

Access detailed error objects for more granular error handling:

try {
schema.validateSync(data, { abortEarly: false });
} catch (errors) {
console.error(errors.errors);
}

6. Conditional Validation

6.1 When Method

Conditionally apply validation rules based on other field values:

const conditionalSchema = yup.object().shape({
isAdult: yup.boolean().required(),
age: yup.number().when('isAdult', {
is: true,
then: yup.number().min(18, 'Must be at least 18 years old').required(),
otherwise: yup.number().min(0, 'Age cannot be negative').required(),
}),
});

7. Array and Object Validation

7.1 Array Validation

Validate arrays with Yup:

const arraySchema = yup.array().of(yup.number().positive().integer());

7.2 Object Shape Validation

Validate objects with a specific shape:

const shapeSchema = yup.object().shape({
name: yup.string().required(),
address: yup.object().shape({
street: yup.string().required(),
city: yup.string().required(),
}),
});

8. Localization and Custom Validation

8.1 Localization

Localize error messages by setting the locale:

yup.setLocale({
string: {
email: 'Invalid email format',
},
});

8.2 Custom Validation

Implement custom validation methods when needed:

yup.addMethod(yup.string, 'isUpperCase', function () {
return this.test('isUpperCase', 'Must be uppercase', function (value) {
if (value && value === value.toUpperCase()) {
return true;
}
return false;
});
});

9. Integration with Form Libraries

9.1 Using with Formik

Integrate Yup seamlessly with Formik for form handling:

import { useFormik } from 'formik';

const formik = useFormik({
initialValues: {
username: '',
email: '',
age: '',
},
validationSchema: schema,
onSubmit: values => {
// Handle form submission
},
});

9.2 Using with React Hook Form

Incorporate Yup with React Hook Form:

import { useForm } from 'react-hook-form';

const { register, handleSubmit, errors } = useForm({
validationSchema: yupResolver(schema),
});

10. Best Practices and Advanced Techniques

10.1 Yup Middleware

Explore advanced techniques like Yup middleware for centralized validation logic.

10.2 Testing Strategies

Implement testing strategies for Yup schemas using tools like Jest.

Conclusion

Yup provides a robust and flexible solution for form validation in web applications. By mastering the concepts, methods, and techniques covered in this guide, you can confidently implement and customize form validation logic, ensuring data integrity and enhancing the user experience. Whether you are working with simple input fields or complex form structures, Yup empowers you to create reliable and user-friendly web forms.