【问题标题】:Yup and react hook form input validation bug是的和反应钩子表单输入验证错误
【发布时间】:2021-07-07 19:13:08
【问题描述】:

我的输入验证有问题。当我提交并出现错误消息时验证有效,但是当我按下键盘上的第一个键时,文本区域中没有任何内容出现并且错误消息消失;之后就可以正常写了。这是一个不便,我不知道它为什么会发生。我正在使用 Material UI 中的 TextArea。登录表单的代码sn-p如下。


const schema = yup.object().shape({
  username: yup.string().matches(/^[a-z0-9]+$/, 'Must be all lower-case letters.').required(),
  password: yup.string().required(),
})

const Login = props =>  {
  const [formValues, setFormValues] = React.useState({
    username: "",
    password: ""
  });

  const { register,errors, handleSubmit } = useForm({
    resolver: yupResolver(schema),
    mode: 'onSubmit',
  });


  const onSubmit = async (data, e) => {
    e.preventDefault()
    const isValid = await schema.isValid(data)
    if(isValid){
      console.log(data);
    }
  }

  return (
    <Container component="main" maxWidth="xs">
      <div>
        <form onSubmit={handleSubmit(onSubmit)}>
          <TextField
            autoFocus
            required
            fullWidth
            id="username"
            label="Username"
            name="username"
            value={formValues.username}     
            inputRef={register}         
            helperText = {errors.username?.message}
          />
          <TextField
            required
            fullWidth
            name="password"
            label="Password"
            type="password"
            id="password"
            value={formValues.password}
            inputRef={register}
            helperText = {errors.password?.message}
          />
          <Button
            type="submit"
            fullWidth
            className={classes.submit}
          >
            Login
          </Button>
        </form>
      </div>
    </Container>
  );
}

【问题讨论】:

标签: javascript reactjs yup react-hook-form


【解决方案1】:

我通过在 useForm() 选项中使用 reValidateMode:"onBlur" 解决了这个问题(在 React Native 中)。

这样在用户离开输入之前它不会重试验证。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-15
    • 2018-01-02
    • 2020-09-07
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 2021-01-19
    相关资源
    最近更新 更多