【发布时间】:2021-11-01 16:05:50
【问题描述】:
我有一个包含一系列电子邮件的表单。数组没有大小限制。我需要检查数组中的每个元素都是有效的电子邮件。用户应该能够向数组中添加新元素,并且应该至少有一封电子邮件,并且每个新元素都应该有一个有效的电子邮件,并且每封电子邮件都应该是唯一的。我希望只有在用户第一次提交表单后才能进行验证。验证电子邮件列表的正确方法应该是什么?
我正在使用 Ant Design 组件,并将无效电子邮件的索引列表保留为 invalidArrayIndexes,以便我可以在每个无效行上显示错误。当我添加新元素时,我无法收到所需的消息(“请输入您的电子邮件!”),并且当我添加或删除新元素时,已验证的索引列表变得混杂。我不确定这是否是在反应中验证字符串列表的正确方法。这是我到目前为止所做的:
import { Button, Form, Input } from "antd";
import { useState } from "react";
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const isValidEmail = (str) => {
return emailRegex.test(str);
};
const MyForm = () => {
const [emails, setEmails] = useState([""]);
const [invalidArrayIndexes, setInvalidArrayIndexes] = useState([]);
const [firstSubmit, setFirstSubmit] = useState(false);
const addEmail = () => {
const updatedEmails = [...emails];
updatedEmails.push("");
setEmails(updatedEmails);
};
const removeEmail = (index) => {
const updatedEmails = [...emails];
updatedEmails.splice(index, 1);
setEmails(updatedEmails);
};
const formSubmitted = () => {
if (!firstSubmit) {
setFirstSubmit(true);
}
const notValidEmails = emails.filter((email) => {
return !isValidEmail(email);
});
const invalidEmailExist = notValidEmails.length > 0;
if (!invalidEmailExist) {
console.log("now submitting");
console.log(emails);
}
};
const valChanged = (e, index) => {
const updatedEmails = [...emails];
updatedEmails[index] = e.target.value;
if (firstSubmit) {
const isValid = isValidEmail(e.target.value);
if (isValid) {
if (invalidArrayIndexes.indexOf(index) > -1) {
const updatedInvalidArrayIndexes = [...invalidArrayIndexes];
updatedInvalidArrayIndexes.splice(
updatedInvalidArrayIndexes.indexOf(index),
1
);
setInvalidArrayIndexes(updatedInvalidArrayIndexes);
}
} else {
if (invalidArrayIndexes.indexOf(index) < 0) {
const updatedInvalidArrayIndexes = [...invalidArrayIndexes];
updatedInvalidArrayIndexes.push(index);
setInvalidArrayIndexes(updatedInvalidArrayIndexes);
}
}
}
setEmails(updatedEmails);
};
const emailList = emails.map((email, index) => {
return (
<Form.Item
key={index}
name="email"
label="email"
rules={[{ required: true, message: "Please enter your email!" }]}
validateStatus={invalidArrayIndexes.includes(index) && "error"}
help={invalidArrayIndexes.includes(index) ? "not a valid email" : " "}
>
<Input
style={{ width: 300 }}
placeholder="enter email"
value={email}
onChange={(e) => valChanged(e, index)}
/>
<Button type="label" onClick={() => removeEmail(index)}>
remove email
</Button>
</Form.Item>
);
});
return (
<div>
{emailList}
<Button type="label" onClick={addEmail}>
add new email
</Button>
<div style={{ marginTop: 20 }}>
<Button type="primary" onClick={formSubmitted}>
send emails
</Button>
</div>
</div>
);
};
export default MyForm;
【问题讨论】:
标签: arrays reactjs validation antd