微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

我正在尝试验证我们使用 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}
            />

解决方法

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

helperText={errors.firstname}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。