I have an application that I developed with react native. I'm using react-hook-form on both login and registration screens. and I have a validation schema that I created myself. I can't use this validation scheme with react-hook-form controller's rules because I can't assign 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')}`;
};
I created a simple example with React js not React Native (will not be a 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<FormValues>({mode: 'onChange'});
console.log(errors);
return (
<form onSubmit={handleSubmit((data) => console.log(data))}>
<Controller
control={control}
name="email"
render={({ field: { onChange, onBlur, value, ref } }) => (
<input onChange={onChange} onBlur={onBlur} />
)}
rules={{
validate: {
required: (value) => emailValidation(value)
},
}}
/>
<input type="submit" />
</form>
);
}
sandbox example here