gpt4 book ai didi

javascript - 在 JavaScript 中添加和删除属性

转载 作者:行者123 更新时间:2023-12-01 04:10:19 24 4
gpt4 key购买 nike

我的问题是,当我单击“提交”时,它应该仅为空字段添加 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>

最佳答案

您的 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;
}

这是一个有效的代码笔链接, http://codepen.io/nadirlaskar/pen/rjOEJQ

关于javascript - 在 JavaScript 中添加和删除属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41562737/

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