I want to validate a form using yup, the problem is that when I want to loop the errors thrown by yup, I find out that the last filed that I enter is not valid:
const schema = yup.object().shape({
age: yup.number().required("age is required"),
name: yup.string().required("name is required"),
email : yup.string().required("email is required"),
});
try{
schema.validateSync({form}, {abortEarly: false})
}catch(e:any){
let err = {
age : '',
name : '',
email : '',
}
e.inner.forEach(error => {
err[error.path] = error.message
})
}
console.log(err)
When I fill the name and age firstly, then I will get error say email is not valid even I fill it:
let form = {
age : '32', // filled first
name : 'mike', // filled second
email : '[email protected]', // filled last
}
I got :
err = {
age : '',
name : '',
email : 'email is required',
}
same thing with the name if I fill age and email, generally last field it will not be validated, any solutions?
CodePudding user response:
This line: schema.validateSync({form}, {abortEarly: false})
should be schema.validateSync({...form}, {abortEarly: false})
or
schema.validateSync(form, {abortEarly: false})
.
schema.validateSync({form}) will validate the object {form: form} not
{
age : '32',
name : 'mike',
email : '[email protected]',
}