DEV Community

Cover image for How to handle form Validation in React ?
Hillary Chibuko
Hillary Chibuko

Posted on

How to handle form Validation in React ?

Today I bring you the ultimate way to handle form validation in a react application with a library called formik.

Formik makes form validation as easy as ......
lets get straight to the point....

npm install formik and thats it, we will also be making use of yup which may be used with Formik but it ain't mandatory if you feel comfortable writing your own form validation

import { useFormik } from "formik"
import * as Yup from "yup"
const FormValidation =()=>{

const signup =(e)=>{
const formik = useFormik({
initialValues:{
name:"",
email:"",
password:""
},

validationSchema:Yup.object({
name:Yup.string().required('this field is
required'),
email:Yup.string().email('invalid email
type').required('this field is required'),
password:Yup.string().max(16,"password must
not be more than 16 characters").required('required')
}),

onSubmit =() =>{
  alert(JSON.stringify(values))
}
Enter fullscreen mode Exit fullscreen mode

})
}

return (

  <input id="name" name="name" type="text"
   onBlur={formik.handleBlur} onChange= 
  {formik.handleChange}/>
   {formik.errors.name && formik.touched.name 
  ? <div>{formik.errors.name} </div> : ""}


  <input id="email" name="email" type="text" 
  onBlur={formik.handleBlur}
  onChange= 
  {formik.handleChange}/>
   {formik.errors.email && 
        formik.touched.email ? <div> 
    {formik.errors.email} </div> : ""}

  <input id="password" name="password" type="text" onBlur={formik.handleBlur}
  onChange= 
  {formik.handleChange}/>

   {formik.errors.password && formik.touched.password ? <div>{formik.errors.password} </div> : ""}

);
}
This is pretty much all you need to get started using formik and yup....

for detailed information checkout www.formik.org/docs/tutorial

Top comments (0)