使用正则表达式的表单验证不起作用 TextField MUI React

Form validation using regex is not working TextField MUI React

我正在尝试在 inputProps 中添加一个正则表达式模式以验证文本字段和 required 但两者都不起作用,点击下一步时也会输入空的或错误的输入。

  <TextField
            id="outlined-basic"
            name="s_firstName"
            label="First Name"
            variant="outlined"
            defaultValue={user.s_firstName}
            onChange={handleChange} 
           
            inputProps={{pattern: "[a-z]"}
            required />

请问验证不工作是什么问题?

您的代码看起来不错,如果您提交表单,required 可以正常工作。它显示哪个字段是 requi红色,标签上有标记。

在materialui,

required bool
If true, the label is displayed as required and the input element is required.

您会在输入内容时看到一个警告弹出窗口。

为了验证,您可以使用 onChange 编写自己的函数。

  const handleValidation = (e) => {
    const reg = new RegExp("[a-z]");
    setValid(reg.test(e.target.value));
    setValue(e.target.value);
  };

有了 <Textfield>error 道具,你可以做这样的事情,

          <TextField
            id="outlined-basic"
            name="s_firstName"
            label="First Name"
            variant="outlined"
            value={value}
            onChange={(e) => handleValidation(e)}
            error={!valid}
            required={true}
          />

查看此 demo 两个场景的代码。