formik seterrors重置其他字段
我有一个表格,我在其中使用formik和验证范围,例如
const formik = useFormik({
enableReinitialize: true,
initialValues: {
name: insurer && get(insurer, "name", null),
surname: insurer && get(insurer, "surname", null),
postalCode: insurer && get(insurer, "postalCode", null),
},
onSubmit: (values: any) => {},
validationSchema: Yup.object().shape({
name: Yup.string()
.typeError("Preenche este campo")
.required("Preenche este campo"),
surname: Yup.string()
.typeError("Preenche este campo")
.required("Preenche este campo"),
}),
});
,您可以看到我有三个字段名称,即Surename和PosteralCode,我还为姓名和姓氏定义了验证,邮政编码,我正在击中一个api,返回falses对于无效的邮政编码,
因此当我提交表格时,我会看到
Object { surname: "Preenche este campo", name: "Preenche este campo" }
现在的错误,如果我开始键入邮政代码,我会从API中收到错误,然后将其设置
formik.setErrors({postalCode:'error in postal code' });
类似
console.log(formik.errors)
为 仅查看此字段的错误,然后重置另一个字段错误
Object { postalCode: "error in postal code" }
I have a form where i am using formik with the validations like
const formik = useFormik({
enableReinitialize: true,
initialValues: {
name: insurer && get(insurer, "name", null),
surname: insurer && get(insurer, "surname", null),
postalCode: insurer && get(insurer, "postalCode", null),
},
onSubmit: (values: any) => {},
validationSchema: Yup.object().shape({
name: Yup.string()
.typeError("Preenche este campo")
.required("Preenche este campo"),
surname: Yup.string()
.typeError("Preenche este campo")
.required("Preenche este campo"),
}),
});
As you can see i have three fields name, surename and postalCode, where i also have defined validation for name and surname, for postalCode, i am hitting an api which is returns false for invalid postalCode
So when initially i submit the form i see error of
Object { surname: "Preenche este campo", name: "Preenche este campo" }
Now if i start typing the postal code i receive error from api and then i set this like
formik.setErrors({postalCode:'error in postal code' });
but now when i console log
console.log(formik.errors)
I only see error for this field, and the other field error are resetted
Object { postalCode: "error in postal code" }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
formik.seterrors
应用于所有错误,{postalcode:'邮政编码中的错误'}
只是许多其他错误的特定错误,因此,当您将其设置为单独时,已经消除了所有其他字段的错误。在这种情况下,您应该将其他字段的错误
formik.errors
与更新的错误一起。formik.setErrors
is applied to all errors,{postalCode:'error in postal code' }
is only a particular error of many other errors, so when you set it singularly that has wiped out all other fields' errors.In this case, you should pass the other fields' errors
formik.errors
to that function along with your updated error.