0
votes

I have a problem in the input validation. The validation works when I submit and a error message appears, but when I press the first key on the keyboard nothing appears in the textarea and the error message disappears; after that, I can write normally. Its an inconvenience and I don't know why its happening. I am using the TextArea from Material UI. The code snippet of a login form is below.


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>
  );
}
1
Change the mode to onChange in useForm, react-hook-form.com/api/useformJoris

1 Answers

0
votes

I worked around this (in React Native) by using reValidateMode:"onBlur" in the useForm() options.

This way it doesn't retry the validation until the user leaves the input.