我的表单中有自定义密码验证功能。在同一个表单上,我对所有其他字段使用 HTML5 验证。我想知道是否有一种在 HTML5 验证中包含此功能的好方法?这是我的自定义密码验证功能的示例:
$('#myaccount-password').keyup(checkPsw).focus(function() {
$('#pswd_info').show();
}).blur(function() {
$('#pswd_info').hide();
});
function checkPsw() {
var pswd = $(this).val();
//validate the length
if (pswd.length < 8) {
$('#length').removeClass('valid').addClass('invalid');
} else {
$('#length').removeClass('invalid').addClass('valid');
}
//validate letter
if (pswd.match(/[a-z]/)) {
$('#letter').removeClass('invalid').addClass('valid');
} else {
$('#letter').removeClass('valid').addClass('invalid');
}
//validate capital letter
if (pswd.match(/[A-Z]/)) {
$('#capital').removeClass('invalid').addClass('valid');
} else {
$('#capital').removeClass('valid').addClass('invalid');
}
//validate special character
if (pswd.match(/(?=.*[?!@])/)) {
$('#character').removeClass('invalid').addClass('valid');
} else {
$('#character').removeClass('valid').addClass('invalid');
}
//validate number
if (pswd.match(/\d/)) {
$('#number').removeClass('invalid').addClass('valid');
} else {
$('#number').removeClass('valid').addClass('invalid');
}
}
.password-container {
position: relative;
}
#pswd_info {
position: absolute;
font-size: .875em;
}
#pswd_info::before {
content: "\25B2";
position: absolute;
top: -12px;
left: 45%;
font-size: 14px;
line-height: 12px;
color: #337ab7;
text-shadow: none;
display: block;
}
#pswd_info ul {
margin: 0;
padding: 0;
}
#pswd_info li {
list-style: none;
}
.invalid {
color: #ec3f41;
}
.valid {
color: #3a7d34;
}
#pswd_info {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group required password-container">
<label class="control-label" for="password">Password</label>
<input type="password" class="form-control" name="myaccount-password" id="myaccount-password" placeholder="Enter Password" maxlength="64" required>
<div id="pswd_info" class="panel panel-primary">
<div class="panel-heading">
<h5>Password requirements:</h5>
</div>
<div class="panel-body">
<ul>
<li id="letter" class="invalid">At least <strong>one letter</strong></li>
<li id="capital" class="invalid">At least <strong>one capital letter</strong></li>
<li id="number" class="invalid">At least <strong>one number</strong></li>
<li id="character" class="invalid">At least <strong>one special character</strong></li>
<li id="length" class="invalid">Be at least <strong>8 characters</strong></li>
</ul>
</div>
</div>
</div>
这是我用于提交表单的函数的示例:
$('#frm-myForm').on('submit', function(e){
e.preventDefault();
var formData = $('#frm-myForm').serialize();
$.ajax({
type: 'POST',
url: 'AjaxFunctions.cfc?method=myForm',
data: formData,
dataType: 'json'
}).done(function(obj){
console.log(obj);
}).fail(function(jqXHR, textStatus, errorThrown){
alert("Error: "+errorThrown);
});
});
上面的函数将触发 HTML5 验证,但不会检查我的密码是否有效。有没有办法在处理表单提交之前检查是否满足所有密码要求?提前致谢。