英文:
Formik validation is not showing after the modification
问题
我对 Formik 还不太了解。我搜索了几次,但没有找到可行的解决方案。
所以我需要您的帮助来解决这个问题。
我的 Formik 表单如下所示,
<Formik initialValues={initialValues} onSubmit={onSubmit}>
<Form>
<div>
<div>
<div>
<Field
type="text"
id="firstName"
name="firstName"
className="form-control"
placeholder="名字"
validate={ValidateName}
/>
<ErrorMessage name="firstName">
{msg => <div style={errorMsg}>{msg}</div>}
</ErrorMessage>
</div>
</div>
</div>
</Form>
</Formik>
之后,我添加了以下修改,
const searchParams = new URLSearchParams(document.location.search);
const [firstName, setFirstName] = useState(searchParams.get("firstName") || "");
<div className="col-md-6 col-sm-12">
<div className="form-group">
<Field
type="text"
id="firstName"
name="firstName"
className="form-control"
placeholder="名字"
onChange={(e) => setFirstName(e.target.value)}
validate={ValidateName}
value={firstName}
/>
<ErrorMessage name="firstName">
{msg => <div style={errorMsg}>{msg}</div>}
</ErrorMessage>
</div>
</div>
所有都正常工作,但验证消息未显示在表单中。ValidateName 返回错误消息。
请告诉我我在哪里出错了。谢谢!
英文:
I'm new to formik. i searched couple of times and didn't find a working solution.
so i need your help to resolve this issue.
my formik form as below,
<Form>
<div>
<div>
<div>
<Field
type="text"
id="firstName"
name="firstName"
className="form-control"
placeholder="First Name"
validate={ValidateName}
/>
<ErrorMessage name="firstName">
{msg => <div style={errorMsg}>{msg}</div>}
</ErrorMessage>
</div>
</div>
after that i added some modification as below,
const searchParams = new URLSearchParams(document.location.search);
const [firstName, setFirstName] = useState(searchParams.get("firstName") || "");
<div className="col-md-6 col-sm-12">
<div className="form-group">
<Field
type="text"
id="firstName"
name="firstName"
className="form-control"
placeholder="First Name"
onChange={(e) => setFirstName(e.target.value)}
validate={ValidateName}
value={firstName}
/>
<ErrorMessage name="firstName">
{msg => <div style={errorMsg}>{msg}</div>}
</ErrorMessage>
</div>
</div>
all are working fine, but validation message is not showing in the form. ValidateName returning error message
please let me know where i did the mistake. Thanks
答案1
得分: 1
这里以下的部分:
{msg => <div style={errorMsg}>{msg}</div>}
应该改成如下:
{msg && <div style={errorMsg}>{msg}</div>}
英文:
This here below.
{msg => <div style={errorMsg}>{msg}</div>}
should be as below.
{msg && <div style={errorMsg}>{msg}</div>}
答案2
得分: 0
已排序。当我清除输入并单击输入框外部时,显示了错误消息。感谢所有关注我的问题的人。
英文:
Sorted. When I cleared the input and clicked outside the input, an error message was shown. Thank you to everyone who looked into my problem.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论