In my previous blog, I explained form handling in React using Formik (a third-party library) and touched on form validation using Yup. But in this article, we are going to take a deeper look and master form validation in react. This complete guide teaches you, how easy it is to do form validation with great user experience.
If you have ever built a form, you might have faced the daunting task of validating user input. However, as the form grows, it becomes unmanageable, and achieving a good user experience becomes challenging.
With Yup, it becomes super simple and we developers feel confident and thus a great user experience is provided along the way.
### Prerequisites & Setup
Before, we start diving into the validation with Yup, make sure that you have a basic understanding of react and state management. We're going to use Formik for form handling in this article, so I suggest you have a basic understanding of Form Handling with Formik, although it is optional. Yup can be used with other frameworks and libraries.
Installation
Once you have React installed and running, install Formik & yup using the below command.
npm install formik yup
# OR with Yarn
yarn add formik yup
Once installed you're ready to start building forms and validating forms.
What is Yup?
Yup is a third-party library for schema builder values parsing and validation for frontend applications. Using this schema developers define the set of rules for validating strings, numbers, arrays, objects, and custom validation with regex and conditional validation.
Getting Started with Form Validation
In this article, we'll see how to use Yup with Formik useFormik() hook to validate our input fields.
The useFormik() allows us to define the Yup validation schema for user input values. See the example below:
import { useFormik } from "formik";
import * as Yup from "yup";
export default function LoginForm() {
// initial values
const initialValues = {
username: "",
password: ""
}
// Yup validation schema
const validationSchema = Yup.object({
username: Yup.string().required('Username is required'),
password: Yup.string().required('Password is required'),
});
const formik = useFormik({
initialValues,
validationSchema: validationSchema,
onSubmit: (values) => {
// submit form
}
});
return (
{/* UI here */}
)
}
1) Validating User Email Validation
The below code snippets validate user email with email() method, making this field mandatory and must be filled with required() method.
const validationSchema = Yup.object({
email: Yup.string().email('Invalid email format').required('Email is required'),
});
2) Numeric Value Range Validation
Validating numeric values like numbers with number() method and validating a range can be done using min() & max() methods.
const validationSchema = Yup.object({
age: Yup.number().min(18, 'Must be at least 18').max(65, 'Must be 65 or younger').required('Age is required'),
});
3) Boolean Value Validation
To validate the boolean value Yup provides a boolean() method.
const validationSchema = Yup.object({
agreeTerms: Yup.boolean().oneOf([true], 'You must accept the terms'),
});
4) Validating a website URL
As the URL type is a string so string() method is used with url() to validate any URL.
const validationSchema = Yup.object({
website: Yup.string().url('Must be a valid URL').required('Website is required'),
});
5) Basic Form Validation (Login Form Example)
Here is an example of The basic Login Form.
const validationSchema = Yup.object({
username: Yup.string().required('Username is required'),
password: Yup.string().required('Password is required'),
});
6) Validating/Matching 2 Values (Confirm Password Example)
Most of the time when we try to Reset Password || Change Password. We allow users to confirm/review passwords. This makes sure that both passwords are the same. Yup, make it easy with conditional validation using oneOf() method.
const validationSchema = Yup.object({
password: Yup.string().required('Password is required'),
confirmPassword: Yup.string()
.oneOf([Yup.ref('password')], 'Passwords must match')
.required('Confirm password is required'),
});
7) Password Strength Validation (Multiple Criteria)
Yup parse and validate faster and with the help of these methods we can achieve complex validation like password strength validation.
const validationSchema = Yup.object({
password: Yup.string()
.min(8, 'Password must be at least 8 characters')
.matches(/[a-z]/, 'Must contain a lowercase letter')
.matches(/[A-Z]/, 'Must contain an uppercase letter')
.matches(/[0-9]/, 'Must contain a number')
.matches(/[@$!%*?&]/, 'Must contain a special character')
.required('Password is required'),
});
8) Validating Date Field
Dates can be a complex topic most of the time and the validation.... with Yup we can easily validate dates using the date() method. In this snippet, the max() method is used with the date to validate if a user is at least 18 years old or above.
const validationSchema = Yup.object({
birthDate: Yup.date().max(new Date(Date.now() - 567648000000), 'Must be at least 18 years old').required('Required'),
});JavaScript
9) Validate Date Range Field (Start & End Date)
We can also validate between two dates using date() method with min & max methods as shown in the below example.
const DateRangeSchema = Yup.object().shape({
startDate: Yup.date()
.min(new Date(1990, 0, 1), 'Start date cannot be before 1990')
.max(new Date(2020, 11, 31), 'Start date cannot be after 2020')
.required('Start date is required'),
endDate: Yup.date()
.min(Yup.ref('startDate'), 'End date must be after start date')
.max(new Date(2020, 11, 31), 'End date cannot be after 2020')
.required('End date is required'),
});
10) Array List Validation
If we want to validate an array of strings we can achieve it using array() method.
const validationSchema = Yup.object({
tags: Yup.array().of(Yup.string().required('Tag is required')),
});
11) Validating Array of Object
The array might have a different set of data types, we can store any kind of data. Validating an array of objects with deep field validation can also be achieved using our array method.
const validationSchema = Yup.object({
employees: Yup.array().of(
Yup.object({
name: Yup.string().required('Name is required'),
age: Yup.number().min(18, 'Must be at least 18').required('Age is required'),
})
),
});
12) Working with a Nested Object Fields Validation
Just like arrays, we can also validate only objects or nested objects using the object() method. If we look at the below code you will see that we can validate nested objects up to three levels with a custom error message.
const validationSchema = Yup.object({
user: Yup.object({
profile: Yup.object({
firstName: Yup.string().required('First name is required'),
lastName: Yup.string().required('Last name is required'),
}),
}),
});JavaScript
13) Validating User Input using Regex
One of the most powerful ways for custom user input validation we use is regular express. Yup allow us to use regex using different methods.
Here we are using match() method to validate username using regular expressions.
const validationSchema = Yup.object({
username: Yup.string().matches(/^[a-zA-Z0-9_]*$/, 'Only letters, numbers, and underscores are allowed').required('Username is required'),
});
14) Conditional Validation based (Based on Other Field Value)
Conditional validation in Yup offers conditional validation in different ways. In this example we'll see how to validate user input based on another input value.
const validationSchema = Yup.object({
hasDiscount: Yup.boolean(),
discountCode: Yup.string().when('hasDiscount', {
is: true,
then: Yup.string().required('Discount code is required'),
otherwise: Yup.string().notRequired(),
}),
});
15) Conditional Validation based (Based on self Value)
As we discussed in the previous example, conditional validation can be achieved using different ways. In this example, we will see how to validate input using self-value.
const validationSchema = Yup.object({
username: Yup.string().when('username', {
is: (val) => val && val.length > 5,
then: Yup.string().max(15, 'Max 15 characters allowed'),
}),
});
16) Upload File Validation
File validation is another time-consuming and complex validation, but with Yup, we can do so much more with ease. This example shows Upload file validation for file size and file format.
const validationSchema = Yup.object({
file: Yup.mixed()
.test('fileSize', 'File too large', (value) => !value || (value && value.size <= 2000000)) // 2MB
.test('fileFormat', 'Unsupported Format', (value) => !value || (value && ['image/jpeg', 'image/png'].includes(value.type))),
});
17) Validating Pre-defined Values
Sometimes we wanted to validate input to match our pre-defined input values. This example demonstrates the best use of pre-defined values validation using oneOf() method.
const validationSchema = Yup.object({
status: Yup.mixed().oneOf(['active', 'inactive', 'pending'], 'Invalid status').required('Status is required'),
});
18) API Based validation (username)
I like this way of doing live validation. This example shows how to validate input values like username and match the records from the database with the help of our API. This is so much fun to do that way.
// api function
const checkUsernameAvailability = async (username) => {
// Mock API response: assume the API returns `true` if the username is available
const response = await fetch(`/api/check-username?username=${username}`);
const data = await response.json();
return data.isAvailable;
};
// validation schema
const validationSchema = Yup.object({
username: Yup.string()
.required('Username is required')
.test('username-available', 'Username is taken', async (value) => {
const isAvailable = await checkUsernameAvailability(value);
return isAvailable;
}),
});
Wrapping up
Yup, its own is a small library for validation purposes. It's popular among in React and most used with Formik. Yup is an incredibly versatile and powerful tool for handling form validation.
It offers us a declarative and readable syntax, making it easy to manage complex logic in a wide range of scenarios.
By using Yup, we can validate input data types, handle complex logic, work with nested values, and do conditional validation.
One big benefit is, that our code can be easily maintainable, easy to read, and saves our time.
This Blog Originally Posted at Programmingly.dev
Please Join our Newsletter for Latest & Trending Web development & Design Articles
Top comments (0)