Text field validation in material UI using error property

Viewed 12102

I am trying to set an error property in my React UI app, such that when the text box exceeds a maximum number of characters, then the error property is set, and the text box is highlighted in a red colour. I am basing the logic from https://mui.com/components/text-fields/#validation

However, the red colour is only presented when the user clicks outside of the textbox; it remains as the default colour until this event occurs.

Can you tell me if its possible to render the red error colour around the text box without the need for having to click outside of the text box, i.e. whilst the user is within the textbox.

Text field:-

<TextField
  fullWidth
  rowsMax={1}
  autoFocus="autofocus"
  className={classes.textField}
  id={modalConfig.textField.id}
  helperText={textInputErrorMessage}
  label={modalConfig.textField.label}
  placeholder={modalConfig.textField.placeholder}
  variant="outlined"
  value={textName}
  onChange={handleTextChange}
  error={textInputError}
/>

and my function:-

function handleTextChange(e) {
    setTextName(e.target.value);
    const checkedMaxTextLength = checkMaxTextLength(e.target.value);
    const checkedZeroTextLength = e.target.value.length === 0;
    setSaveDisabled(checkedMaxTextLength || checkedZeroTextLength);
    setTextInputError(checkedMaxTextLength);
    if (checkedMaxTextLength) {
      setTextInputErrorMessage("The input has exceeded the maximum number of characters");
    } else {
      setTextInputErrorMessage(null);
    }
  }
1 Answers

Hey this is pretty easy to achieve if you are using the TextField as a controlled component(you are using state to handle the input value) you could actually just perform a boolean validation to check if the value is more than your max length value show the error, for example this is using 10 as the max value:

import * as React from "react";
import TextField from "@mui/material/TextField";

const MAX_LENGTH = 10;

export default function ValidationTextField() {
  const [text, setText] = React.useState("");
  const [errorMessage, setErrorMessage] = React.useState("");

  React.useEffect(() => {
    // Set errorMessage only if text is equal or bigger than MAX_LENGTH
    if (text.length >= MAX_LENGTH) {
      setErrorMessage(
        "The input has exceeded the maximum number of characters"
      );
    }
  }, [text]);

  React.useEffect(() => {
    // Set empty erroMessage only if text is less than MAX_LENGTH
    // and errorMessage is not empty.
    // avoids setting empty errorMessage if the errorMessage is already empty
    if (text.length < MAX_LENGTH && errorMessage) {
      setErrorMessage("");
    }
  }, [text, errorMessage]);

  return (
    <TextField
      error={text.length >= MAX_LENGTH}
      id="outlined-error"
      label="Error"
      helperText={errorMessage}
      onChange={(e) => setText(e.target.value)}
      value={text}
    />
  );
}

Notice how we are passing the error prop like this: error={text.length >= MAX_LENGTH} so if your input passes the MAX_LENGTH it will show the error, the useEffects are to check whether you should show an error message depending your input text length. With this you should be able to validate as you want. Here's a code sandbox in case you want to check the result: https://codesandbox.io/s/validationtextfields-material-demo-forked-x2m45

Related