gpt4 book ai didi

javascript - 验证表 : how to show error message all at one time for the blank input instead of one by one?

转载 作者:行者123 更新时间:2023-11-29 19:42:16 26 4
gpt4 key购买 nike

我想验证我的表单,如果任何输入字段为空,错误警告将显示在空白输入字段旁边。对于空白输入,错误信息必须一次全部输出,而不是一一显示。如何做到这一点?

下面是我的javascript代码:

    function doValidate()
{
var x=document.forms["form"]["fullname"].value;
if (x==null || x=="")
{
document.getElementById('error1').innerHTML="Full name is required!";
return false;
}

var y=document.forms["form"]["uid"].value;
if (y==null || y=="")
{
document.getElementById('error2').innerHTML="Username is required!";
return false;
}

var z=document.forms["form"]["pwd"].value;
if (z==null || z=="")
{
document.getElementById('error3').innerHTML="Password is required!";
return false;
}

var a=document.forms["form"]["pwd2"].value;
if (a==null || a=="")
{
document.getElementById('error4').innerHTML="Please re-enter your password!";
return false;
}

var pwd = document.getElementById("pwd").value;
var pwd2 = document.getElementById("pwd2").value;
if(pwd != pwd2){
alert('Wrong confirm password!');
return false;
}

var b=document.forms["form"]["role"].value;
if (b==null || b=="Please select...")
{
document.getElementById('error5').innerHTML="Please select user role!";
return false;
}

}

最佳答案

您应该使用 var ok = true 开始您的函数,并且在每个 if block 中,您应该不要让 return false设置 ok = false。最后返回ok

这可能是这样的:

function doValidate() {
var ok = true;

var form = document.forms.form;

var fullname = form.fullname.value;
if (fullname == null || fullname == "") {
document.getElementById('error1').innerHTML = "Full name is required!";
ok = false;
}

var uid = form.uid.value;
if (uid == null || uid == "") {
document.getElementById('error2').innerHTML = "Username is required!";
ok = false;
}

var pwd = form.pwd.value;
if (pwd == null || pwd == "") {
document.getElementById('error3').innerHTML = "Password is required!";
ok = false;
}

var pwd2 = form.pwd2.value;
if (pwd2 == null || pwd2 == "") {
document.getElementById('error4').innerHTML = "Please re-enter your password!";
ok = false;
} else if (pwd != pwd2) {
document.getElementById('error4').innerHTML = "Wrong confirm password!";
ok = false;
}

var role = form.role.value;
if (role == null || role == "Please select...") {
document.getElementById('error5').innerHTML = "Please select user role!";
ok = false;
}

return ok;
}

(我已经冒昧地更改为更一致的格式样式,改进了一些变量名,简化了一些访问模式,并像其他一样将 alert 替换为内联错误消息。 )

关于javascript - 验证表 : how to show error message all at one time for the blank input instead of one by one?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22319094/

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