We can make form validation of our own with custom hook, but there is a good library for that already, Formik.

Formik provide useForm hook for implementing the validation into our regular form. The first step of using Formik is installing the dependency, lol, also we need a validator function to perform validation.

const validate = values => {   const errors = {};    if (!values.password) {     errors.password = 'Required';   } else if (values.password.length < 6) {     errors.password = 'Must be must be 6 or more characters';   }   if (!values.name) {     errors.name = 'Name Required';   } else if (values.name.length < 1) {     errors.name = 'Minimum of 2 characters';   } }

It is just another JavaScript function, which check the parameter value and return some object.

useFormik

Let's create Formik object,

 const formik = useFormik({     initialValues: {       email: 'martin@gmail.com',       name: 'Martin Thomas',        },     validate,     onSubmit: (values) => {        alert(JSON.stringify(values, null, 2));     },   }); 

The useForm hook provide handleSubmit, handleChange, handleBlur, isSubmiting event handlers and properties' , where handleBlur watching the revisited input change and the isSubmiting return true if there is no error.

Initial values

Create initial values for the form input, it can be expressed as simple object

Validate

Validation can be schema , or a function, we can also use external libraries such as yum for schema generation. For our case it is a function

 const validate = values => {   const errors = {};    if (!values.password) {     errors.password = 'Required';   } else if (values.password.length < 6) {     errors.password = 'Must be must be 6 or more characters';   }   if (!values.name) {     errors.name = 'Name Required';   } else if (values.name.length < 1) {     errors.name = 'Minimum of 2 characters';   }   if (!values.email) {     errors.email = 'Required';   } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) {     errors.email = 'Invalid email address';   }   if (!values.lid) {     errors.lid = 'Required';   }    if (!values.cid) {     errors.cid = 'Required';   }    return errors; }; 

onSubmit

We can wrap submission logic in this handler.

Add validation to the form

In the form section we can us the handlers as formik.handlerName also the value can can be accessed from the value Object. The error object can be use to display the error messages.

 import React from 'react'; import { useFormik } from 'formik'; import Button from "@mui/material/Button";  import CssBaseline from "@mui/material/CssBaseline"; import TextField from "@mui/material/TextField";  import Grid from "@mui/material/Grid"; import Box from "@mui/material/Box";  import Typography from "@mui/material/Typography"; import Container from "@mui/material/Container"; import { createTheme, ThemeProvider } from "@mui/material/styles";    ....  const formik = useFormik({     initialValues: {       email: 'martin@gmail.com',       name: 'Martin Thomas',        },     validate,     onSubmit: (values) => {        alert(JSON.stringify(values, null, 2));     },   }); <div>       <ThemeProvider theme={theme}>         <Container component="main" maxWidth="xs">           <CssBaseline />           <Box             sx={{               marginTop: 8,               display: "flex",               flexDirection: "column",               alignItems: "center",             }}           >                          <Box               component="form"               onSubmit={formik.handleSubmit}               sx={{ mt: 3 }}             >                <Grid container spacing={2}>                 <Grid item xs={12} sm={12}>                   <TextField                     autoComplete="given-name"                     name="name"                     required                     fullWidth                     id="name"                     label="Name"                     onBlur={formik.handleBlur}                     value={formik.values.name}                     onChange={formik.handleChange}                     error={formik.touched.name && Boolean(formik.errors.name)}                     helperText={formik.touched.name && formik.errors.name}                     autoFocus                   />                 </Grid>                  <Grid item xs={12}>                   <TextField                     required                     fullWidth                     id="email"                     onBlur={formik.handleBlur}                     label="Email Address"                     name="email"                     autoComplete="email"                     value={formik.values.email}                     onChange={formik.handleChange}                     error={formik.touched.email && Boolean(formik.errors.email)}                     helperText={formik.touched.email && formik.errors.email}                   />                 </Grid>                                                 <Button                 type="submit"                  disabled={formik.isSubmitting}                 fullWidth                 variant="contained"                 sx={{ mt: 3, mb: 2 }}               >                 Sign Up               </Button>                             </Box>           </Box>               </Container>       </ThemeProvider>            </div> 

Integrating Formik with Form and Mui so easy.


This free site is ad-supported. Learn more