文本字段上的反应材料 ui 表单验证不起作用

时间:2021-03-26 10:51:38

标签: reactjs validation material-ui textfield

我正在尝试验证我们使用 mui 构建的 React 表单。我想使用 mui 文本字段错误属性来显示错误消息。验证在提交时启动,但未显示错误消息。任何帮助都会非常有用。谢谢。

  const history = useHistory();
  const [errors, setErrors] = useState({});
  const [open, setOpen] = useState(false);

  const initialFormState = {
    firstname: '',
    lastname: '',
    username: '',
    contactnumber: '',
    password: '',
    confirmPass: '',
  };
  const [registration, setRegistration] = useState(initialFormState);

  const validate = () => {
    let temp = {...errors};
    if ('firstname' in registration)
      temp.firstname = registration.firstname ? '' : 'This field is required.';
    if ('lastname' in registration)
      temp.lastname = registration.lastname ? '' : 'This field is required.';
    if ('username' in registration)
      temp.username = /$^|.+@.+..+/.test(registration.username)
        ? ''
        : 'Email is not valid.';
    if ('contactnumber' in registration)
      temp.contactnumberr =
        registration.contactnumber.length > 6
          ? ''
          : 'Minimum 6 numbers required.';
    if ('password' in registration)
      temp.password =
        registration.password.length != 0 ? '' : 'This field is required.';
    setErrors({
      ...temp,
    });

    if (registration) return Object.values(temp).every((x) => x == '');
  };

  const handleChange = (e) => {
    setRegistration({
      ...registration,
      [e.target.name]: e.target.value,
    });
  };
 <TextField
              variant="outlined"
              margin="normal"
              id="first name"
              label="First Name"
              style={{margin: 8}}
              fullWidth
              name="firstname"
              value={registration.firstname}
              onChange={handleChange}
              className={classes.root}
              error={errors.firstname}
            />

1 个答案:

答案 0 :(得分:0)

Material UI 文本字段带有辅助文本属性:

helperText={errors.firstname}