gpt4 book ai didi

Javascript - 我的表单验证出现问题

转载 作者:行者123 更新时间:2023-12-02 22:35:56 28 4
gpt4 key购买 nike

我的 php 表单 发送电子邮件的验证脚本有问题,尽管它可以很好地验证表单,但当用户单击“接受”时警报按钮,脚本不会阻止操作,并且表单仍会发送...

我做错了什么?

提前致谢!

HTML:

<div id="form">
<section>
<form action="send.php" method="post" accept-charset='UTF-8'>
<label for="email"></label>
<input id="email" type="email" name="email" maxlength="50">
<input type="hidden" name="privacy" value="blahblahblah"/>

<input id="submit" type="submit" name="submit" value="SEND" onclick="validate(this);">

</div>
</form>
</section>
</div>

脚本(验证):

function validate () {
var email;
email = document.getElementById("email").value;
expresion = /\w+@\w+\.+\w/;

if(email === "") {
alert("You cannot submit this request. You must give us an email");
return false;
}

else if (email.length>50) {
alert("The maximum for email is 50 characters");
return false;
}

else if (!expresion.test(email)) {
alert("Check your information. The email format is not valid");
return false;
}
}

最佳答案

将事件更改为 onsubmit 并将其放在表单上。

function validate () {
var email;
email = document.getElementById("email").value;
expresion = /\w+@\w+\.+\w/;

if(email === "") {
alert("You cannot submit this request. You must give us an email");
return false;
}

else if (email.length>50) {
alert("The maximum for email is 50 characters");
return false;
}

else if (!expresion.test(email)) {
alert("Check your information. The email format is not valid");
return false;
}
console.log('passed!');
}
<div id="form">
<section>
<form action="" method="post" accept-charset='UTF-8' onsubmit="return validate(this);">
<label for="email"></label>
<input id="email" type="email" name="email" maxlength="50">
<input type="hidden" name="privacy" value="blahblahblah"/>

<input id="submit" type="submit" name="submit" value="SEND">
</form>
</section>
</div>

关于Javascript - 我的表单验证出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58737241/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com