我有一個使用 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粉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 ( ); }
沙箱範例這裡