Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 36 ยท Inputs and Forms

Form Validation with MUI

Build validated forms with Material UI: touched state, error and helperText, submit handling, focusing the first error, accessibility, and React Hook Form with Controller.

You now know the individual inputs. A real form combines them with validation: checking the data, telling the user what is wrong, and only submitting when everything is valid. MUI does not validate for you; it gives you the visual states (error, helperText, required) and you supply the logic. This lesson shows a robust pattern, then how React Hook Form and Zod automate it.

Principles of good validation UX

  1. Validate on blur and on submit, not on every keystroke for the first time: nobody wants "invalid email" after typing one letter. Once a field has an error, re-validate while typing so the message clears as soon as it is fixed.
  2. Say what is wrong and how to fix it: "Password must have at least 8 characters", not "Invalid".
  3. Show errors next to the field with helperText, and consider a summary at the top for long forms.
  4. Do not rely on color: the text carries the meaning.
  5. Validate again on the server. Client validation is convenience; the server is the authority.

The state you need

A form with validation typically tracks three things:

  • values: what the user typed.
  • touched: which fields the user has left (blurred) or tried to submit.
  • errors: derived from the values with a pure function validate(values).

Because errors is derived, do not store it in state; compute it during render (or with useMemo). The rule: state is the source of truth, errors follow from it. See choosing state structure.

JSX
const validate = (v) => {
  const errors = {};
  if (!v.name.trim()) errors.name = 'Name is required';
  if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(v.email)) errors.email = 'Enter a valid email address';
  if (v.password.length < 8) errors.password = 'Use at least 8 characters';
  return errors;
};

A pure function like this is easy to test without any UI. Try it in the next example, which is plain JavaScript.

JS A pure validate function you can test

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A complete controlled form

Putting the pieces together with MUI components (real MUI code, read-only):

JSX
import { useState } from 'react';
import Stack from '@mui/material/Stack';
import TextField from '@mui/material/TextField';
import Button from '@mui/material/Button';
import FormControlLabel from '@mui/material/FormControlLabel';
import Checkbox from '@mui/material/Checkbox';
import FormHelperText from '@mui/material/FormHelperText';

export default function SignUp() {
  const [values, setValues] = useState({ name: '', email: '', password: '', agree: false });
  const [touched, setTouched] = useState({});
  const errors = validate(values);

  const handleChange = (event) => {
    const { name, type, value, checked } = event.target;
    setValues((v) => ({ ...v, [name]: type === 'checkbox' ? checked : value }));
  };
  const handleBlur = (event) => setTouched((t) => ({ ...t, [event.target.name]: true }));

  const handleSubmit = (event) => {
    event.preventDefault();
    setTouched({ name: true, email: true, password: true, agree: true }); // show all errors
    if (Object.keys(errors).length === 0) {
      submit(values);
    }
  };

  const show = (field) => touched[field] && errors[field];

  return (
    <form onSubmit={handleSubmit} noValidate>
      <Stack spacing={2} sx={{ maxWidth: 400 }}>
        <TextField
          name="name" label="Name" required
          value={values.name} onChange={handleChange} onBlur={handleBlur}
          error={Boolean(show('name'))} helperText={show('name') || ' '}
        />
        <TextField
          name="email" label="Email" type="email" autoComplete="email" required
          value={values.email} onChange={handleChange} onBlur={handleBlur}
          error={Boolean(show('email'))} helperText={show('email') || ' '}
        />
        <TextField
          name="password" label="Password" type="password" autoComplete="new-password" required
          value={values.password} onChange={handleChange} onBlur={handleBlur}
          error={Boolean(show('password'))} helperText={show('password') || ' '}
        />
        <FormControlLabel
          control={<Checkbox name="agree" checked={values.agree} onChange={handleChange} onBlur={handleBlur} />}
          label="I accept the terms"
        />
        {show('agree') && <FormHelperText error>{errors.agree}</FormHelperText>}
        <Button type="submit" variant="contained">Create account</Button>
      </Stack>
    </form>
  );
}

Points worth noticing:

  • noValidate on the <form> turns off the browser's own bubbles, so MUI's messages are the only ones shown. Keep HTML attributes (required, type="email") for semantics and mobile keyboards.
  • A shared handleChange uses name to update any field; checkboxes read checked.
  • On submit we mark every field touched so all errors appear at once.
  • error={Boolean(...)} because error expects a boolean, while the message is a string.

Stand-in: the whole pattern, running

This stand-in implements the form above with plain inputs styled like MUI fields. Try submitting empty, then fix fields one at a time. Errors appear after blur or submit and disappear as soon as the value becomes valid. A live region announces the submit result, and focus jumps to the first invalid field.

Stand-in: sign-up form with touched state and error summary

React Hook Form with MUI

Hand-written forms get repetitive. React Hook Form (RHF) manages values, touched state and errors with fewer re-renders, and Zod (or Yup) describes validation as a schema. MUI inputs are controlled components, so connect them with RHF's Controller. This is real library code (read-only; the packages are not available in our editor):

JSX
import { useForm, Controller } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';

const schema = z.object({
  name: z.string().min(1, 'Name is required'),
  email: z.string().email('Enter a valid email address'),
  password: z.string().min(8, 'Use at least 8 characters'),
});

export default function SignUp() {
  const { control, handleSubmit, formState: { isSubmitting } } = useForm({
    resolver: zodResolver(schema),
    defaultValues: { name: '', email: '', password: '' },
    mode: 'onBlur',
  });

  return (
    <form onSubmit={handleSubmit(async (data) => { await save(data); })} noValidate>
      <Stack spacing={2}>
        <Controller
          name="email"
          control={control}
          render={({ field, fieldState }) => (
            <TextField
              {...field}
              label="Email"
              error={fieldState.invalid}
              helperText={fieldState.error?.message ?? ' '}
            />
          )}
        />
        {/* same for name and password */}
        <Button type="submit" variant="contained" disabled={isSubmitting}>Create account</Button>
      </Stack>
    </form>
  );
}

field carries value, onChange, onBlur, name and ref, so spreading it into a MUI input just works. fieldState has the error. mode: 'onBlur' matches the validation timing we described. The full integration, including Select and Autocomplete, is also covered in React Hook Form with Zod.

Accessibility checklist for forms

  • Every input has a visible label (label prop) and the right autoComplete.
  • Error messages are in helperText (connected through aria-describedby automatically) and say how to fix the problem.
  • On submit failure, move focus to the first invalid field, or to an error summary with role="alert".
  • Disable the submit button only while sending, not as the way to signal invalid data: a disabled button gives no explanation.
  • Mark required fields; explain the meaning of * once near the top if needed.

Common mistakes

  • Keeping errors in state and forgetting to update it, so messages go stale. Derive them instead.
  • Showing every error immediately on first render. Use touched or submit state.
  • Passing a string to error (it needs a boolean).
  • Trusting client validation only.
  • Letting the layout jump when messages appear: use helperText={' '} as a placeholder.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which props show an error message on a TextField?

    error turns on the error styling; helperText holds the message the user reads.
  2. 2. Why track a touched state per field?

    Showing errors only after blur or submit prevents annoying messages on untouched fields.
  3. 3. What does noValidate on a form do?

    It prevents native validation popups; your MUI error states take over, while attributes still help semantics.
  4. 4. How do you connect a controlled MUI input to React Hook Form?

    Controller bridges RHF to controlled components and gives you field and fieldState.
  5. 5. Why should errors usually be derived rather than stored in state?

    A validate(values) function recomputed each render always matches the current data.

Summary

  • MUI provides error, helperText and required; you provide the validation logic.
  • Track values and touched, derive errors with a pure validate function, and show messages after blur or submit.
  • Use noValidate, mark all fields touched on submit and focus the first invalid field.
  • For larger forms, React Hook Form with Controller and a Zod schema removes boilerplate.
  • Keep forms accessible: labels, autoComplete, clear messages, focus management, and always validate on the server too.

Next: Theme Basics and ThemeProvider