Is it possible to use optional field with pattern? #4270
-
Hi, I've got a question regarding form validation. If I'd like to create a form with optional field, that includes const MyForm = () => {
const initialValues = {
name: 'John Doe',
};
const {
register,
handleSubmit,
formState: { errors, isValid },
} = useForm({ defaultValues: initialValues, mode: 'onChange' });
const onSubmit = (data) => console.log({ data });
const isEmailPattern = /^[_a-z0-9-\+]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9]+)*(\.[a-z]{2,})$/i;
console.log({ errors, isValid });
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input name="name" ref={register({ required: true })} />
<input
name="email"
ref={register({ required: false, pattern: isEmailPattern })}
/>
<input type="submit" disabled={!isValid} />
</form>
);
}; On initial render, form is not valid ( I would expect not |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
it's easier to do |
Beta Was this translation helpful? Give feedback.
it's easier to do
validate
function or schema validation libraries like zod, yup and etc...