How to create form validation with Yup library in Reactjs

Olivier Trinh
2 min readAug 18, 2023

--

Form validation is an important part of any web application. It helps to ensure that the data entered by users is correct and complete. Yup is a popular validation library for Reactjs that makes it easy to create and manage form validation.

To use Yup, you first need to install it with npm: npm install yup

Once Yup is installed, you can start creating your validation schema. A validation schema is an object that defines the rules for validating the data in your form.

For example, the following schema validates a username and password:

const schema = Yup.object().shape({
username: Yup.string().required(),
password: Yup.string().required().minLength(8),
});

The required() rule indicates that the field is required. The minLength() rule indicates that the field must be at least 8 characters long.

You can then use the validate() method to validate the data in your form:

const formData = {
username: "user123",
password: "password123",
};

const errors = schema.validate(formData);

if (errors.length > 0) {
// There are errors in the form data
} else {
// The form data is valid
}

The errors object will contain an array of error messages if the form data is not valid.

Yup also provides a number of other validation rules, such as email(), url(), and number(). You can find a full list of the available validation rules in the Yup documentation.

Here is an example of how to use Yup to validate a form that allows users to create a new account:

const schema = Yup.object().shape({
username: Yup.string().required().minLength(3).maxLength(25),
email: Yup.string().email().required(),
password: Yup.string().required().minLength(8).maxLenght(25),
});

const handleSubmit = (e) => {
e.preventDefault();

const formData = {
username: e.target.username.value,
email: e.target.email.value,
password: e.target.password.value,
};

const errors = schema.validate(formData);

if (errors.length > 0) {
// There are errors in the form data
alert(errors.join("\n"));
} else {
// The form data is valid, do something with it
}
};

const App = () => {
return (
<form onSubmit={handleSubmit}>
<input type="text" name="username" placeholder="Username" />
<input type="email" name="email" placeholder="Email" />
<input type="password" name="password" placeholder="Password" />
<button type="submit">Create Account</button>
</form>
);
};

This example uses the onSubmit event handler to validate the form data when the user clicks the submit button. If the form data is valid, the code does something with it. Otherwise, it displays an error message.

--

--