Form validation is a crucial part of any application form, we need to put validation in such a way that the user doesn't fill in the wrong details. We also need to show the appropriate message when a user enters any invalid details.
In the previous article, we have seen how to manage react forms with Formik. In this article, we will go further with form validation, we will see how to setup form validation schema, and show the appropriate message.
So let's get started.
Form Validation with Formik
" Formik is designed to manage forms with complex validation with ease. Formik supports synchronous and asynchronous form-level and field-level validation - Formik Docs".
Formik supports the schema-based form validation with Yup. Yup is a JavaScript schema builder for value parsing and validation.
We will continue with our previous example at stackblitz.
Install Yup
- npm install --save yup
Create Validation Schema
We will import the yup and create the validation schema as below,
- const validationSchema = yup.object().shape({
- firstName: yup
- .string()
- .required()
- .min(3),
- lastName: yup.string().required(),
- emailId: yup
- .string()
- .required()
- .email(),
- mobileNumber: yup.number()
- });
Here I have not used any validation message when there is an error, So yup will automatically generate a validation message based on the key.
For example,
For example,
- firstName is a required field
- firstName must be at least 3 characters etc.
- const validationSchema = yup.object().shape({
- firstName: yup
- .string()
- .required('First name is required.')
- .min(3, 'Minimum 3 characters required'),
- lastName: yup.string().required('Last name is required'),
- emailId: yup
- .string()
- .required('Email ID is required')
- .email('Enter valid email id'),
- mobileNumber: yup.number()
- });
Use Validation Schema
Now we will set this validation schema with useFormik() hook as shown below. Formik uses this validation schema to validate the input controls when the form state is changed.
- const formik = useFormik({
- initialValues: {
- firstName: '',
- lastName: '',
- emailId: '',
- mobileNumber: undefined,
- gender: '',
- address: ''
- },
- onSubmit: values => {
- alert(
- 'Registration Form Submitted \n ' + JSON.stringify(values, null, 2)
- );
- formik.resetForm();
- },
- validationSchema: validationSchema
- });
Formik State For Error Handling
Formik object provides various state which we can use to handle the error.
- isValid - true when all validation is fulfilled else false.
- dirty - true when the change in any form control value.
- errors - gives the errors of each form control.
We will use this property to show the error message for each control.- {
- "firstName": "First name is required.",
- "lastName": "Last name is required",
- "emailId": "Email ID is required"
- }
- touched - touched state of all the form controls.
- {
- "firstName": true,
- "lastName": true,
- "emailId": true
- }
Show Error Message
Now we will use the above states to show error messages for each form control. We will create one function which will take field name as input and render an error message if control is touched and have an error.
- const renderErrorMessage = field => {
- return (
- formik.touched[field] && (
- <div class="text-error">{formik.errors[field]}</div>
- )
- );
- };
- <div>
- <input type="text" {...formik.getFieldProps('firstName')} />
- { renderErrorMessage('firstName') }
- </div>
We have also added CSS in App.css for .text-error.
Final Code

Join the conversation! Your thoughts help the community grow.