Password error is always true react-hook-form

Viewed 410

I'm trying to make a login in react-native with react-hook-form, but when I come to the login screen the console.log(errors) puts out this line password: {type: "required", message: "Password is required", ref: {…}}

and i don't understand why.

this is my code:

const Login = () => {
  const { control, handleSubmit, formState: { errors } } = useForm({
    defaultValues: {
      username: '',
      password: ''
    }
  });

  const onSubmit = (data) => {
    console.log(data)
  }
    
  return (
      <View>
        <Controller
          defaultValue=""
          name={fields.username}
          control={control}
          render={({ onChange, value }) => (
          <TextInput
            onChange={onChange}
            value={value}
            placeholder='Username'
            rules={{ required: { value: true, message: 'Username is required' } }}
          />
          )}
        />
        {errors.username && <Text>UserName is required.</Text>}
        <Controller
          defaultValue=""
          name={fields.password}
          control={control}
          rules={{
            required: { value: true, message: 'Password is required' },
            minLength: {
              message: 'Use at least 4 characters.',
              value: 4,               
            },
          }}
          render={({ onChange, value }) => (
          <TextInput
            onChange={onChange}
            value={value}
            secureTextEntry={true}
            placeholder='Password'
          />
          )}
        />
        {errors.password?.type === "required" && <Text>Password is required.</Text>}
        
        {errors.password?.type === "minLength" && <Text>Minimum 4 characters are required</Text>}
        {console.log(errors)}
        <Button title='Submit' onPress={handleSubmit(onSubmit)} />
      </View>
  )
}

export default Login;

I'm not sure were the error is, I hope someone can help with this

1 Answers

You have to use the onChangeText prop instead of onChange to receive the current typed input value.

One other minor note: The first <Controller /> misses the rules as you placed it as a prop for the <TextInput />. I corrected it in the CodeSandbox.

Edit RHF - React Native

Related