这很好用,但如果密码字段留空,我需要它也会忽略它。
我希望用户能够在不更改密码的情况下更新其信息。因此,如果他们将密码字段留空,则他们的密码保持不变。
document.addEventListener("DOMContentLoaded", function() {
// JavaScript form validation
var checkPassword = function(str)
{
var re = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}$/;
return re.test(str);
};
var checkForm = function(e)
{
if(this.pwd1.value != "" && this.pwd1.value == this.pwd2.value) {
if(!checkPassword(this.pwd1.value)) {
alert("The password you have entered is not valid!");
this.pwd1.focus();
e.preventDefault();
return;
}
} else {
alert("Error: Please check that you've entered and confirmed your password!");
this.pwd1.focus();
e.preventDefault();
return;
}
};
var add_employee_form = document.getElementById("add_employee_form");
add_employee_form.addEventListener("submit", checkForm, true);
// HTML5 form validation
var supports_input_validity = function()
{
var i = document.createElement("input");
return "setCustomValidity" in i;
}
if(supports_input_validity()) {
var pwd1Input = document.getElementById("field_pwd1");
var pwd1Rule = "Password must contain at least 6 characters, including UPPER/lowercase and numbers.";
pwd1Input.setCustomValidity(pwd1Rule);
var pwd2Input = document.getElementById("field_pwd2");
var pwd2Rule = "Please enter the same Password as above.";
// input onchange event handlers
pwd1Input.addEventListener("change", function() {
this.setCustomValidity(this.validity.patternMismatch ? pwd1Rule : "");
if(this.checkValidity()) {
pwd2Input.pattern = this.value;
pwd2Input.setCustomValidity(pwd2Rule);
} else {
pwd2Input.pattern = this.pattern;
pwd2Input.setCustomValidity("");
}
}, false);
pwd2Input.addEventListener("change", function() {
this.setCustomValidity(this.validity.patternMismatch ? pwd2Rule : "");
}, false);
}
}, false);
</script>
答案 0 :(得分:1)
更改您的功能以将其置于顶部:
if(!this.pwd1.value) return;
对于null或空白的值,javascript将返回false,因此如果为false则返回false。
全功能:
var checkForm = function(e)
{
if(!this.pwd1.value) return;
if(this.pwd1.value != "" && this.pwd1.value == this.pwd2.value) {
if(!checkPassword(this.pwd1.value)) {
alert("The password you have entered is not valid!");
this.pwd1.focus();
e.preventDefault();
return;
}
} else {
alert("Error: Please check that you've entered and confirmed your password!");
this.pwd1.focus();
e.preventDefault();
return;
}
};