我的问题是当我点击提交时,它应该只为空字段添加box
类。但是我的代码为填充和未填充字段添加了box
类。
function validate() {
var a = document.forms["Form"]["uname"].value;
var b = document.forms["Form"]["number"].value;
var c = document.forms["Form"]["mail"].value;
if (a == null || a == "", b == null || b == "", c == null || c == "") {
['uname', 'mobNo', 'mail'].forEach(function(ids) {
document.getElementById(ids).style.border = "1px solid red";
});
return false;
} else if (!a.match(/^([a-zA-Z]{2,30})$/)) {
document.getElementById('uname').className = 'box';
return false;
} else if (!b.match(/^\d*[0-9](|.\d*[0-9]|,\d*[0-9])?$/)) {
document.getElementById('mobNo').className = 'box';
return false;
} else if (!c.match(/^([\w-\.]+@([\w-]+)+(\.[\w-]{2,4})?)$/)) {
document.getElementById('mail').className = 'box';
return false;
}
}
.box {
border: 2px solid red;
}
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<form method="post" name="Form" onsubmit="return validate()" action="" id="form_id">
<fieldset>
<label>NAME:</label>
<input type="text" name="uname" id="uname" class="fields">
<label>MOBILE NUMBER:</label>
<input type="text" name="number" id="mobNo" class="fields" minlength="10" maxlength="10">
<label>EMAIL:</label>
<input type="email" name="mail" id="mail" class="fields">
<button type="submit" name="submit">SUBMIT</button>
</fieldset>
</form>
</body>
</html>
答案 0 :(得分:1)
在:
if (a==null || a=="",b==null || b=="",c==null || c=="")
,
运营商什么也不做;它返回上一次比较:
(c==null || c=="")
请修好
if ((a==null || a=="") && (b==null || b=="") && (c==null || c==""))
答案 1 :(得分:1)
你的if else条件存在错误
您可以通过这种方式验证表单。
function validate() {
var a = document.forms["Form"]["uname"].value;
var b = document.forms["Form"]["number"].value;
var c = document.forms["Form"]["mail"].value;
var validation=true;
if ((a == null || a == "")||(!a.match(/^([a-zA-Z]{2,30})$/))) {
document.getElementById('uname').className = 'box';
validation=false;
} else{
document.getElementById('uname').className = '';
}
if ((b == null || b == "")||(!b.match(/^\d*[0-9](|.\d*[0-9]|,\d*[0-9])?$/))) {
document.getElementById('mobNo').className = 'box';
validation=false;
} else{
document.getElementById('mobNo').className = '';
}
if ((c == null || c == "")||(!c.match(/^([\w-\.]+@([\w-]+)+(\.[\w-]{2,4})?)$/))) {
document.getElementById('mail').className = 'box';
validation=false;
}else{
document.getElementById('mobNo').className = '';
}
return validation;
}
这是一个有效的codepen链接, http://codepen.io/nadirlaskar/pen/rjOEJQ