我有一个多步骤,有一个输入验证。我想在输入字段下显示一个错误文本,而不是显示空输入错误的toast。就像这样:
显然,对于这类错误使用吐司消息不是一个好的做法。
const [formData, setFormData] = useState({
businessName: "",
businessEmail: "",
currency: "",
industry: "",
businessDescription: "",
useCase: "",
organisationType: "",
website: "",
businessPhone: "",
country: "",
billingName: "",
billingEmail: "",
addressState: "",
addressCity: "",
addressStreet: "",
});
const handleSubmit = () => {
if (step === 0) {
if (formData.businessName === "") {
toast({
title: "Error",
description: "Please provide a business name",
status: "error",
position: "top-right",
duration: 3000,
isClosable: true,
});
}
if (formData.businessEmail === "") {
toast({
title: "Error",
description: "Please provide a business email",
status: "error",
position: "top-right",
duration: 3000,
isClosable: true,
});
} else {
setStep(step + 1);
}
} else if (step === 1) {
if (formData.website === "") {
toast({
title: "Error",
description: "Please provide a website",
status: "error",
position: "top-right",
duration: 3000,
isClosable: true,
});
}
if (formData.businessPhone === "") {
toast({
title: "Error",
description: "Please provide a registered phone number",
status: "error",
position: "top-right",
duration: 3000,
isClosable: true,
});
} else {
setStep(step + 1);
}
} else if (step === 2) { ............. and so on.
这是我的表单中的一个步骤:
export default function Account({ formData, setFormData }) {
return (
<Input
placeholder="Business Name"
name="businessName"
onChange={(e) => {
setFormData({
...formData,
businessName: e.target.value,
});
}}
value={formData.businessName}
type="name"
/>
<Input
placeholder="Business Email"
name="businessEmail"
onChange={(e) => {
setFormData({
...formData,
businessEmail: e.target.value,
});
}}
value={formData.businessEmail}
type="email"
/>
......... and so on.
)
1条答案
按热度按时间hgb9j2n61#
表单和状态管理逻辑如下所示
添加错误状态以跟踪每个输入字段是否存在错误:
更新handleSubmit函数以设置错误,而不是显示祝酒词:
修改表单组件以显示错误文本:
现在,当发生错误时,它将存储在相应字段的错误状态中。错误文本将显示在输入字段下方,以红色表示。一旦解决了错误并且提交了没有任何错误的表单,错误状态将被清除,表单可以继续进行下一步。