Why “Yup” is the Best Way to Validate Create and Edit form in React/NextJS.
When building modern web applications, form validation is a fundamental task. Whether you’re creating a new record or editing an existing one, ensuring that the data entered by the user is both accurate and follows the necessary constraints is crucial. One of the best ways to achieve this is by using Yup — a schema validation library that seamlessly integrates with React Hook Form. In this blog, we’ll dive into why Yup is an excellent choice for form validation, especially when dealing with “create” and “edit” forms.
Yup is a JavaScript object schema validator and object parser, built with a fluent API for defining validation rules. It allows you to define validation schemas in a declarative manner, ensuring that data adheres to certain rules before proceeding with form submission or other operations.
const organizationFormSchema = yup.object().shape({
internalName: yup.string().required("internal name is mandatory"),
displayName: yup.string().required("display name is mandatory"),
});
Yup is particularly useful when you need to validate forms in scenarios where users are either creating new records or editing existing ones. It integrates effortlessly with React Hook Form, a popular library that simplifies form management in React, ensuring a smooth and streamlined experience for developers and users alike.
const formOptions = {
resolver: yupResolver(organizationFormSchema),
};
One of the most useful features of Yup is its ability to handle conditional validation. When editing an existing record, certain fields may not need to be validated in the same way as when creating a new record. Yup allows you to easily add conditional validation rules, ensuring that validation adapts based on the context of the form.
const organizationFormSchema = yup.object().shape({
internalName: yup.string().when('isEdit', {
is: true,
then: yup.string(),
otherwise: yup.string().required("Internal name is mandatory"),
}),
displayName: yup.string().required("Display name is mandatory"),
});
Yup supports asynchronous validation, which is useful in cases where you need to check external conditions (e.g., checking if an email is already in use). Asynchronous validation can be extremely helpful in both create and edit scenarios, such as validating unique fields.
const emailSchema = yup.string().email().test(
'email-check',
'Email is already in use',
async (value) => {
const isEmailTaken = await checkIfEmailTaken(value);
return !isEmailTaken;
}
);
the onSubmit
function will only be called once all the validation rules have passed. This means that before the form data is submitted to the server or any other handler, React Hook Form will first run the validation using the Yup schema you defined. If any validation rule fails, the form won't be submitted, and the user will see the validation error messages.
const onSubmit = async (data: any) => {
// This function will only be called if validation passes
console.log(data);
await createOrganization({
variables: {
displayName: data.displayName,
internalName: data.internalName,
},
});
};
In conclusion, by using Yup in your React applications, you can ensure that your forms are well-validated, your data is clean, and your users have a smooth and seamless interaction with your application.