How to add form validation with React and Material UI?

Sometimes, we want to add form validation with React and Material UI.

In this article, we’ll look at how to add form validation with React and Material UI.

How to add form validation with React and Material UI?

To add form validation with React and Material UI, we can set the error prop of the TextField to show the error state when there’s an error.

We can set the helperText prop to show the error message.

For instance, we write:

import React, { useState } from "react";
import { TextField } from "@material-ui/core";

export default function App() {
  const [text, setText] = useState();

  return (
    <div>
      <TextField
        value={text}
        onChange={(event) => setText(event.target.value)}
        error={text === ""}
        helperText={text === "" ? "Empty!" : " "}
      />
    </div>
  );
}

We add a TextField with the value prop set to text to show the inputted text.

And we set the onChange prop to a function that calls setText to set the inputted value as the value of the text prop.

Next, we set the error prop to text === "" to make the input box red when text is an empty string.

Finally, we set the helperText to text === "" ? "Empty!" : " " to check if text is an empty string.

If it is, then we show ‘Empty!`. Otherwise, we show nothing.

Conclusion

To add form validation with React and Material UI, we can set the error prop of the TextField to show the error state when there’s an error.

We can set the helperText prop to show the error message.