搜索

首页  >  问答  >  正文

反应本机react-hook-form控制器规则验证不起作用

我有一个使用 React Native 开发的应用程序。我在登录和注册屏幕上使用react-hook-form。我有一个自己创建的验证模式。我无法将此验证方案与react-hook-form控制器的规则一起使用,因为我无法分配输入值,请帮忙!

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粉445714413252 天前473

全部回复(1)我来回复

  • P粉811329034

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

    我使用 React js 创建了一个简单的示例,而不是 React Native(此处不会有所不同)

    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) }, }} /> ); }

    沙箱示例这里

    回复
    0
  • 取消回复