反應本機react-hook-form控制器規則驗證不起作用
P粉445714413
P粉445714413 2024-03-26 18:35:16
0
1
494

我有一個使用 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粉445714413
P粉445714413

全部回覆(1)
P粉811329034

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

沙箱範例這裡

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板