使用错误属性在材质 UI 中验证文本字段

R11*_*111 1 textbox reactjs material-ui

我试图在我的 React UI 应用程序中设置一个错误属性,这样当文本框超过最大字符数时,就会设置错误属性,并且文本框以红色突出显示。我的逻辑基于https://mui.com/components/text-fields/#validation

然而,只有当用户在文本框之外单击时才会呈现红色;它保持为默认颜色,直到该事件发生。

您能否告诉我是否可以在文本框周围渲染红色错误颜色,而无需在文本框外部单击,即当用户位于文本框内时。

文本域:-

<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}
/>
Run Code Online (Sandbox Code Playgroud)

和我的职能:-

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);
    }
  }
Run Code Online (Sandbox Code Playgroud)

jea*_*182 10

嘿,如果您使用 TextField 作为受控组件(您正在使用状态来处理输入值),那么这很容易实现,您实际上可以执行布尔验证来检查该值是否大于您的最大长度值显示错误,例如使用 10 作为最大值:

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}
    />
  );
}
Run Code Online (Sandbox Code Playgroud)

请注意我们如何像这样传递 error 属性:error={text.length >= MAX_LENGTH}因此,如果您的输入传递了MAX_LENGTH,它将显示错误, useEffects 将检查您是否应该根据输入文本长度显示错误消息。有了这个,您应该能够根据需要进行验证。这是一个代码沙箱,以防您想检查结果: https: //codesandbox.io/s/validationtextfields-material-demo-forked-x2m45