Formik is one of most popular React libraries, for managing forms and validations. It has inbuilt state-management system. The Fomik series of posts will cover all essential topics regarding form management using Formik.
Yup
Using Yup , the validation rules for formik become simpler. I recommend using this library instead of creating new rules.
First up all , install and import the library to your project.
yarn add yup
Create Yup Object
Let’s create simple Yup schema for Formik, based on this schema Formik hook can generate errors for each form fields.
import * as Yup from 'yup'
....
const loginValidationSchema = Yup.object({
email: Yup.string().email('Invalid email format').required('Required'),
password: Yup.string().required('Required'),
});
In the hook we can specify the schema as follows
const formikLogin = useFormik({
initialValues: {
email: '',
password: '',
},
onSubmit: async values => {
console.log(values);
},
validationSchema
});