我有一个handleSubmit函数,在提交表单时触发。我正在收集用户电子邮件作为输入。我现有的代码不会拒绝无效的条目,我不确定我错过了什么......
理想情况下,无效响应会触发警告框,但截至目前,所有输入都被推送到数据库。
const handleSubmit = (e) => {
let participantsName = e.target.participantsName.value;
let participantsEmail = e.target.participantsEmail.value;
let pattern = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
e.preventDefault();
if (participantsName) {
e.target.participantsName.value = "";
Participants.insert({
name: participantsName
});
}
if (participantsEmail.match(pattern)) {
e.target.participantsEmail.value = "";
Participants.insert({
email: participantsEmail
});
alert("Please enter a valid email address")
}
}
答案 0 :(得分:0)
将您的正则表达式更改为更广泛的
let pattern = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
答案 1 :(得分:0)
来自html5的初步验证正则表达式
/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/
扩展
# http://www.w3.org/TR/html5/forms.html#valid-e-mail-address
^
[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+
@
[a-zA-Z0-9]
(?:
[a-zA-Z0-9-]{0,61}
[a-zA-Z0-9]
)?
(?:
\.
[a-zA-Z0-9]
(?:
[a-zA-Z0-9-]{0,61}
[a-zA-Z0-9]
)?
)*
$
答案 2 :(得分:0)
感谢您的所有回复。通过一些小的改动我得到了代码!
const handleSubmit = (e) => {
let participantsName = e.target.participantsName.value;
let participantsEmail = e.target.participantsEmail.value;
let pattern = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
e.preventDefault();
if(participantsName && participantsEmail.match(pattern)){
e.target.participantsName.value = "";
e.target.participantsEmail.value = "";
Participants.insert({
name: participantsName,
email: participantsEmail
});
} else {
e.target.participantsName.value = "";
e.target.participantsEmail.value = "";
alert("Please enter a valid email address")
}
}