gpt4 book ai didi

Javascript:基本 native 表单验证 - 无法验证多个标准

转载 作者:行者123 更新时间:2023-12-03 09:32:21 26 4
gpt4 key购买 nike

尝试学习如何验证表单输入。

输入需要:1 - 不为空。2 - 仅包含字母字符(无数字)。

当我测试时(我现在只关注名字输入字段),它会给出正确的错误消息如果我将其留空。但是,如果我在字段中输入数字,它将提交而不是显示错误消息。

我做错了什么?

HTML:

<form id="frm1">
<fieldset id="controls">
<div>
<label for="firstname">First Name: </label>
<input type="text" id="firstname">
<span id="errFname" class="errmsg">&#42 You must enter a first name</span>
</div>
<div>
<label for="lastname">Last Name: </label>
<input type="text" id="lastname">
</div>
<div>
<input type="submit" value="Submit">
</div>
</fieldset>
</form>

脚本:

    function checkForm(){


document.getElementById("frm1").onsubmit=function() {


//Validate first name: Required, Alphabetic (no numbers)
if(document.getElementById("firstname").value === "") {

document.getElementById("errFname").style.display = "inline";
document.getElementById("firstname").focus();

return false;

} else {

return true;
}//close if


var alphaRegEx = /[a-zA-Z]/;
var alphafname = document.getElementById("firstname").value;

//check if first name has any digits
if (!alphaRegEx.test(alphafname)){

document.getElementById("errFname").style.display = "inline";
document.getElementById("firstname").value="";
document.getElementById("firstname").focus();

return false;

} else {

return true;

}//close if


}//close function

return false;

}//close function (checkForm)


window.onload=checkForm;

最佳答案

问题是您在每个 if block 内返回,这使得整个 submit 回调返回。

您应该创建一个变量并仅在最后返回。像这样的事情:

function checkForm(){


document.getElementById("frm1").addEventListener("submit", function(e) {
var errors = [];

//Validate first name: Required, Alphabetic (no numbers)
if(document.getElementById("firstname").value === "") {

document.getElementById("errFname").style.display = "inline";
document.getElementById("firstname").focus();

errors.push("required");

}


var alphaRegEx = /[a-zA-Z]/;
var alphafname = document.getElementById("firstname").value;

//check if first name has any digits
if (!alphaRegEx.test(alphafname) && errors.length === 0){

document.getElementById("errFname").style.display = "inline";
document.getElementById("firstname").value="";
document.getElementById("firstname").focus();

errors.push("numeric");

}
//If you want, you can do something with your errors, if not, just return
//You should rethink about handling all errors here showing/hiding messages, etc.
if (errors.length > 0) {
e.preventDefault();
return false;
}
return true;


});//close function

}//close function (checkForm)

关于Javascript:基本 native 表单验证 - 无法验证多个标准,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31463300/

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