Password validation in jQuery
by Faisal Khan Janjua
HTML
<input type="password" name="password" />
CSS
input + .error {
color: #F00;
display: block;
font-size: 80%;
}
.error ul {
margin-top: 0;
padding-left: 16px;
}
JavaScript
var passwordText = {
'chars': '<li>must be at least 8 characters long.</li>',
'digit': '<li>must have at least 1 number.</li>',
'upper': '<li>must have at least 1 uppercase letter.</li>',
'lower': '<li>must have at least 1 lowercase letter.</li>',
'spchr': '<li>must have at least 1 special character.</li>'
};
var passwordCases = { 'chars': true, 'digit': true, 'upper': true, 'lower': true, 'spchr': true };
var passwordError = '<span class="error">Please meet password criteria:<ul></ul></span>';
$(document).on('input blur', 'input[type="password"]', function(){
var that = $(this);
that.next('.error').remove();
var digit = new RegExp("^(?=.*\\d).+$");
var upper = new RegExp("^(?=.*[A-Z]).+$");
var lower = new RegExp("^(?=.*[a-z]).+$");
var spchr = new RegExp("^(?=.*\\W).+$");
passwordCases.chars = that.val().length >= 8 ? true : false;
passwordCases.digit = digit.test(that.val()) ? true : false;
passwordCases.upper = upper.test(that.val()) ? true : false;
passwordCases.lower = lower.test(that.val()) ? true : false;
passwordCases.spchr = spchr.test(that.val()) ? true : false;
var hasError = false;
Object.keys(passwordCases).forEach(function(k) {
if(passwordCases[k] === false) { hasError = true; }
});
if(hasError){
validateFields.password = false;
that.after(passwordError);
Object.keys(passwordCases).forEach(function(k) {
if(passwordCases[k] === false) {
that.next().find('ul').append(passwordText[k]);
}
});
}
else { validateFields.password = true; }
validateRegForm(that);
});
var validateFields = { 'email': false, 'password': false }
function validateRegForm(field){
if(field.closest('form').parent('.wpum-registration-form').length){
if(validateFields.email === true && validateFields.password === true) {
field.closest('form').find('[type="submit"]').removeAttr('disabled');
}
else { field.closest('form').find('[type="submit"]').attr('disabled','disabled'); }
}
}