专家,我需要一点帮助。我有一个JSP页面,需要完成三个验证:
- 密码强度(使用实时检查,而不是validate()函数)
- 确认密码(使用validate()函数,而非实时检查)
- 电子邮件验证(使用实时检查,而不是validate()函数)
实时检查由keyUp()
函数和相应的jQuery完成:
$(document).ready(function(){
$("#register-form").validate({
rules: {
password_again: {
equalTo: "#password"
}
}
});
$("#validate").keyup(function(){
var email = $("#validate").val();
if(email != 0)
{
if(isValidEmailAddress(email))
{
$("#validEmail").css({
"background-image": "url('validate/validYes.png')"
});
} else {
$("#validEmail").css({
"background-image": "url('validate/validNo.png')"
});
}
} else {
$("#validEmail").css({
"background-image": "none"
});
}
});
$('#password').keyup(function(){
$('#result').html(checkStrength($('#password').val()));
});
function checkStrength(password){
//initial strength
var strength = 0;
//if the password length is less than 6, return message.
if (password.length < 6) {
$('#result').removeClass();
$('#result').addClass('short');
return 'SHORT';
}
//length is ok, lets continue.
//if length is 8 characters or more, increase strength value
if (password.length > 7) strength += 1;
//if password contains both lower and uppercase characters, increase strength value
if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) strength += 1;
//if it has numbers and characters, increase strength value
if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/)) strength += 1;
//if it has one special character, increase strength value
if (password.match(/([!,%,&,@,#,$,^,*,?,_,~])/)) strength += 1;
//if it has two special characters, increase strength value
if (password.match(/(.*[!,%,&,@,#,$,^,*,?,_,~].*[!,%,&,@,#,$,^,*,?,_,~])/)) strength += 1;
//now we have calculated strength value, we can return messages
//if value is less than 2
if (strength < 2 ) {
$('#result').removeClass();
$('#result').addClass('weak');
return 'WEAK';
} else if (strength == 2 ) {
$('#result').removeClass();
$('#result').addClass('good');
return 'GOOD';
} else {
$('#result').removeClass();
$('#result').addClass('strong');
return 'STRONG';
}
}
});
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
return pattern.test(emailAddress);
}
一切都运行良好,但是当点击提交按钮后,除了Confirm_Password验证之外,我无法阻止页面转发,如果其中任何一个验证(Confirm_Password、Password_Strength、Email)失败。我希望也能限制对Email和Password_Strength的操作。这意味着每当验证失败时,将焦点设置在该字段上。
请注意,validate()
函数仅用于Confirm_Password。
keyup
处理程序中使用一些 jQuery 来确认两个密码字段是否相等(比较两个字段),然后由于你大多数时间都没有使用它,可以完全删除 jQuery Validate 插件。 - Sparky