how to use form validation with react mui 5 using react-hook-form

How to Use Form Validation with React MUI 5 Using react-hook-form

updated 02/12/23 By frontendshape

In this tutorial, we'll see form validation in React Material UI 5 with the help of react-hook-form. Ensure you have React MUI 5 and react-hook-form installed and configured before getting started.

How to Use react-hook-form in React with MUI 5


React MUI 5 Form Validation With React Hook Form

1. Create simple validation in react mui 5 using useForm, Controller react-hook-form.

import { TextField, Button } from '@mui/material';
import { useForm, Controller } from 'react-hook-form';

export default function App() {
  const { control, handleSubmit, formState: { errors } } = useForm();


  const onSubmit = (data) => {
    console.log(data);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)} style={{margin:"400px"}}>
      <Controller
        name="myField"
        control={control}
        defaultValue=""
        rules={{ required: true }}
        render={({ field }) => (
          <TextField
            {...field}
            label="My Field"
            variant="outlined"
            size="small"
            error={!!errors.myField}
            helperText={errors.myField ? "This field is required" : null}
          />
        )}
      />
      <Button type="submit" variant="contained">Submit</Button>
    </form>
  );
};
mui react-hook-form validation

mui react-hook-form validation

2. React mui 5 form validation using react-hook-form and Typescript.

import { TextField, Button } from '@mui/material';
import { useForm, Controller, SubmitHandler } from 'react-hook-form';

interface FormValues {
  myField: string;
}

export default function App() {
  const { control, handleSubmit, formState: { errors } } = useForm<FormValues>();

  const onSubmit: SubmitHandler<FormValues> = (data) => {
    console.log(data);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Controller
        name="myField"
        control={control}
        defaultValue=""
        rules={{ required: true }}
        render={({ field }) => (
          <TextField
            {...field}
            label="My Field"
            variant="outlined"
            size="small"
            error={!!errors.myField}
            helperText={errors.myField ? "This field is required" : null}
          />
        )}
      />
      <Button type="submit" variant="contained">Submit</Button>
    </form>
  );
}


3. Build a login form with validation in React MUI 5 using useForm, Controller react-hook-form.

import { useForm, Controller } from 'react-hook-form';
import { TextField, Button, Container, Typography } from '@mui/material';

const App = () => {
  const { control, handleSubmit, formState: { errors } } = useForm();

  const onSubmit = (data) => {
    console.log(data);
  };

  return (
    <Container maxWidth="sm">
      <Typography variant="h4" align="center" marginY={2}>Login Form</Typography>
      <form onSubmit={handleSubmit(onSubmit)}>
        <Controller
          name="email"
          control={control}
          defaultValue=""
          rules={{
            required: 'Email is required',
            pattern: {
              value: /^\S+@\S+$/i,
              message: 'Invalid email format'
            }
          }}
          render={({ field }) => (
            <TextField
              {...field}
              label="Email"
              variant="outlined"
              margin="normal"
              fullWidth
              error={!!errors.email}
              helperText={errors.email?.message}
            />
          )}
        />
        <Controller
          name="password"
          control={control}
          defaultValue=""
          rules={{
            required: 'Password is required',
            minLength: {
              value: 6,
              message: 'Password must be at least 6 characters'
            }
          }}
          render={({ field }) => (
            <TextField
              {...field}
              label="Password"
              type="password"
              variant="outlined"
              margin="normal"
              fullWidth
              error={!!errors.password}
              helperText={errors.password?.message}
            />
          )}
        />
        <Button type="submit" variant="contained" color="primary" fullWidth>
          Login
        </Button>
      </form>
    </Container>
  );
};

export default App;
mui react-hook-form login form validation

mui react-hook-form login form validation