I'm using react-hook-form library and yup to validate input fields :
const { handleSubmit, register, errors } = useForm({
mode: 'onBlur',
validationSchema: Yup.object({
name: Yup.string().max(6, 'Max 6 chars').required('Required boy'),
pass: Yup.string().min(6, 'Min 6 chars').required('Required boy')
})
});
const submit = (e) => {
alert(e.name + ' ' + e.pass);
};
return (
<div className="App">
<form onSubmit={handleSubmit(submit)}>
<input id="name" type="text" name="name" ref={register} />
{errors.name && <div>{errors.name.message}</div>}
<input id="pass" type="password" name="pass" ref={register} />
{errors.pass && <h3>{errors.pass.message}</h3>}
<button type="submit">Submit</button>
</form>
</div>
);
It doesn't throw an error in the console and it alerts when I click submit button but the validation doesn't work at all .
I expect the error message to show up when the input is touched and the value is less or more than the required value .
How can I use yup properly with react-hook-form ?
validate
option (there are a couple others, that do simple validation as well butvalidate
is the only customizable one). – Elias Schablowskiyup
that is compatible with thevalidate
option. (e.g.async value => fieldSchema.isValid(value)
) - Although for your use case you can also use theminLength
andmaxLenghth
options. – Elias Schablowski