I see in the docs
<input
{...register("test1", {
validate: {
positive: v => parseInt(v) > 0,
lessThanTen: v => parseInt(v) < 10,
checkUrl: async () => await fetch(),
}
})}
/>
So here how can i show different messages for each validation.
like number is -5, then i show
"Number is not positive"
"Number less than 10"
HOw to access each error positive and lessThanTen
Per default RHF will only show one error per field, so if there are multiple you will you don't have to loop over them. You can just use the errors object provided by RHF and access the name of your field and then the message property.
If you need to have all errors to be shown simultaneously you can set the config criteriaMode, check the docs here for more info.
function App() {
const {
register,
handleSubmit,
formState: { errors }
} = useForm();
const onSubmit = (data) => {
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<label htmlFor="test1">Test Field</label>
<input
{...register("test1", {
validate: {
positive: (v) => parseInt(v) > 0 || "Number is not positive",
lessThanTen: (v) => parseInt(v) < 10 || "Number less than 10",
checkUrl: async () => {
const result = await Promise.resolve(true);
return result || "result was false so show this message";
}
}
})}
/>
{errors.test1 && <p>{errors.test1.message}</p>}
<input type="submit" />
</form>
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With