1
votes

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 ?

2
Which version of react-hook-forms are you using? - Elias Schablowski
@EliasSchablowski the latest version and yes it was the version problem , I solved the issue by installing version 4.9.8 . - Mahdi Faraji
@EliasSchablowski Do you know how validation is handled in the latest version ? - Mahdi Faraji
Validation is handled by the register hook the validate option (there are a couple others, that do simple validation as well but validate is the only customizable one). - Elias Schablowski
Not directly, but you can write your own wrapper around yup that is compatible with the validate option. (e.g. async value => fieldSchema.isValid(value)) - Although for your use case you can also use the minLength and maxLenghth options. - Elias Schablowski

2 Answers

2
votes

Solved the issue by installing version 4.9.8

2
votes

You can use the latest version without downgrading it to 4.9.8

The documentation is in advance section of react hook form under "Custom Hook with Resolver" https://react-hook-form.com/advanced-usage

my sample code below: https://codesandbox.io/s/react-hook-form-yup-material-ui-8ino9