Categories
React Answers

How to invalidate a TextField in React Material UI?

Spread the love

Sometimes, we want to invalidate a TextField in React Material UI.

In this article, we’ll look at how to invalidate a TextField in React Material UI.

How to invalidate a TextField in React Material UI?

To invalidate a TextField in React Material UI, we set the error and helperText props of the TextField to display the error message we want.

For instance, we write:

import React from "react";
import TextField from "@material-ui/core/TextField";

const phoneRegex = /^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$/;

export default function App() {
  const [errorText, setErrorText] = React.useState();
  const [phone, setPhone] = React.useState();

  const onChange = (event) => {
    if (event.target.value.match(phoneRegex)) {
      setErrorText("");
      setPhone(event.target.value);
    } else {
      setErrorText("invalid format");
    }
  };

  return (
    <div>
      <TextField
        label="Phone"
        name="phone"
        helperText={errorText}
        error={errorText}
        onChange={onChange}
        value={phone}
      />
    </div>
  );
}

We set the error prop to make the TextField‘s border red when we enter invalid input.

And we set the helperText prop to display the error text at the bottom.

We set the onChange prop to the onChange function.

It checks whether the ionputted value matches the pattern in the phoneRegex by calling event.target.value.match.

We call setErrorText to set the errorText to set the error message if needed.

And we call setPhone to set the phone state which we use as the value of the TextField‘s value prop to display the inputted value.

Therefore, when we enter invalid text, we see that the text field has a red border.

Conclusion

To invalidate a TextField in React Material UI, we set the error and helperText props of the TextField to display the error message we want.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *