Home  >  Q&A  >  body text

react native react-hook-form controller rule validation not working

I have an application developed using React Native. I'm using react-hook-form for login and registration screens. I have a validation schema that I created. I can't use this validation scheme with the rules of react-hook-form controller because I can't assign the input value, please help!

const formKeys = {
    email: 'email',
    password: 'password',
  };

  const {
    handleSubmit,
    control,
    formState: {errors},
  } = useForm();

<Controller
                control={control}
                name={formKeys.email}
                render={({field: {onChange, value}}) => (
                  <InputFields
                    errorMessage={errors[formKeys.email]?.message.toString()}
                    value={value}
                    onChangeText={onChange}
                    autoCapitalize={'none'}
                    placeholder={t('common:email')}
                    image={
                      <View style={styles.userIconsStyle}>
                        <EmailIcon/>
                      </View>
                    }
                  />
                )}
                rules={{
                  required: emailValidation() //input value required here,
                  minLength: minLengthValidation(validationSchema.email.minLength),
                  maxLength:maxLengthValidation(validationSchema.email.maxLength),
                }}
              />

/*validation schema*/

export const emailValidation = (v: string): boolean | string => {
  const {t,i18n}=useTranslation();
  const emailRegx = /^[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[A-Za-z]+$/;
  if (v) {
    return emailRegx.test(v) || `${t('common:errorMessages:invalidEmailAddress')}`;
  } else return `${t('common:email')} ${t('common:errorMessages:isRequired')}`;
};

P粉445714413P粉445714413178 days ago404

reply all(1)I'll reply

  • P粉811329034

    P粉8113290342024-03-27 11:04:11

    I created a simple example using React js instead of React Native (it won't be different here)

    import { useForm, Controller } from "react-hook-form";
    
    type FormValues = {
      email: string;
    };
    
    const emailValidation = (v: string): boolean | string => {
      // const {t,i18n}=useTranslation();
      const emailRegx = /^[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[A-Za-z]+$/;
      if (v) {
        return emailRegx.test(v) || "invalidEmailAddress";
      } else return "isRequired";
    };
    
    export default function App() {
      const { handleSubmit, control, formState: {errors} } = useForm({mode: 'onChange'});
    
      console.log(errors);
      
      return (
        
    console.log(data))}> ( )} rules={{ validate: { required: (value) => emailValidation(value) }, }} /> ); }

    SandboxExample here

    reply
    0
  • Cancelreply