我正在尝试使用bootstrap和JavaScript验证表单,但我很难获得我的validateForm函数来更改css值。但即使这最终有效,我仍然需要在再次单击提交按钮后重置我的CSS。我应该另辟蹊径吗?这就是我所拥有的:
//section of form
<form name="registration">
<div class="col-xs-6">
<label for="fname">First Name:</label>
<span class = "icon hidden"><a href="#" title="Field Error" data-toggle="popover" data-trigger="hover" data-content="First Name cannot be blank and is not a name format">
<span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true">
</span>
</a></span>
<input class="form-control" name="fname" type="text"><span id="fnameError"></span>
</div>
//more inputs similar format as above, then concluding with the submit button
<button type="submit" class="btn btn-primary" name="signup" value="Sign up" id="regisClick">Register and proceed to checkout</button>
//css
/*error icon*/
.glyphicon-exclamation-sign{
color: red;
}
.hidden>.glyphicon-exclamation-sign{
display: none;
}
/*popover*/
.popover-title{
background-color: red;
color: white;
font-weight: bold;
}
.popover-content{
font-weight: bold;
}
//js
var formInputs = [
[document.forms["registration"]["fname"].value, /^[a-zA-Z]/],
[document.forms["registration"]["lname"].value, /^[a-zA-Z]/],
[document.forms["registration"]["address"].value, /^\d+\s[A-z]+\s[A-z]+/],
[document.forms["registration"]["city"].value, /^[a-zA-Z]+(?:[\s-][a-zA-Z]+)*$/],
[document.forms["registration"]["zipcode"].value, /(^\d{5}$)|(^\d{5}-\d{4}$)/],
[document.forms["registration"]["phone"].value, /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/],
[document.forms["registration"]["email"].value, /^([0-9a-zA-Z]([-_\\.]*[0-9a-zA-Z]+)*)@([0-9a-zA-Z]([-_\\.]*[0-9a-zA-Z]+)*)[\\.]([a-zA-Z]{2,9})$/],
[document.forms["registration"]["password"].value, /(?=.*[A-Za-z])(?=.*\d)(?=.*[$@$!%*#?&])[A-Za-z\d$@$!%*#?&]{8,}$/],
[document.forms["registration"]["confirmPassword"].value, document.forms["registration"]["password"].value],
]
document.getElementById("regisClick").addEventListener("click", validateForm);
function validateForm(inputs){
for(var i=0; i < inputs.length; i++){
if(inputs[i][0] = '' || !inputs[i][1].test(inputs[i][0])){
document.getElementsByClassName("icon hidden")[i].style.display= 'unset';
return false;
}
}
}
感谢您的帮助!