gpt4 book ai didi

javascript - 如何一次验证所有字段?

转载 作者:太空宇宙 更新时间:2023-11-04 10:33:26 26 4
gpt4 key购买 nike

我需要一次验证所有字段,我的意思是如果我在第一个字段中输入文本,其余字段应该显示一条错误消息。

例如,如果我按下带有空字段的提交按钮,它应该显示一条错误消息。

我的 Java 脚本如下所示:

 function check() 
var fName = document.getElementById('mFirstName');
var lName = document.getElementById('mLastName');
var filter = /^[a-zA-Z0-9]+$/;
if (!filter.test(fName.value)) {
document.getElementById("mfnameValidate").style.display = "block";
fName.focus();
return false;
}

if (!filter.test(lName.value)) {
document.getElementById("mlNmaeValidate").style.display = "block";
lName.focus();
return false;
}
function hideError() {
document.getElementById("mfnameValidate").style.display = "none";
}
function hideError2() {
document.getElementById("mlNmaeValidate").style.display = "none";
}

我的 HTML 代码:

<form:form method="post" onsubmit="return check();" action="SignUp"  modelAttribute="memberBean">
<form:input type="text" class="input" name='mFirstName' id='mFirstName' path='mFirstName' placeholder='First Name' onkeydown="hideError()" />
<span id="mfnameValidate">"First Name should not be blank"</span>
<form:input type="text" class="input" name='mLastName' id='mLastName' path='mLastName' placeholder='Last Name' onkeydown="hideError2()" />
<span id="mlNmaeValidate">"Last Name should not be blank"</span>

还有我的 .css:

<style>
span {
color: red;
display: none;
}
</style>

最佳答案

像这样尝试:

document.forms["theForm"].onsubmit = function(e) {
var allInput = getAllElementsWithAttribute('required');
for (key in allInput) {
if (!allInput[key].value) {
e.preventDefault();
allInput[key].className += allInput[key].className.indexOf('invalid') > -1 ? '' : 'invalid';
} else {
console.log(key)
allInput[key].className = allInput[key].className.replace(/\binvalid\b/, '');
}
}
}

function getAllElementsWithAttribute(attribute) {
var matchingElements = [];
var allElements = document.getElementsByTagName('*');
for (var i = 0, n = allElements.length; i < n; i++) {
if (allElements[i].getAttribute(attribute) !== null) {
// Element exists with attribute. Add to array.
matchingElements.push(allElements[i]);
}
}
return matchingElements;
}
.error {
display: none;
color: Red;
}
.invalid+.error {
display: block;
}
<form name="theForm" method="post" novalidate>
<div>
<label>First Name</label>
<input type="text" required>
<span class="error">First Name is required</span>
</div>
<div>
<label>Last Name</label>
<input type="text" required>
<span class="error">Last Name is required</span>
</div>
<input type="submit" value="Submit" />
</form>

还有一个 fiddle :https://jsfiddle.net/rmrinmoy/xnLzjhgy/3/

关于javascript - 如何一次验证所有字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36352338/

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