Created
June 6, 2013 11:43
-
-
Save jamsesso/5720939 to your computer and use it in GitHub Desktop.
Validate a password field based on regular expression tests.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* jQuery validatePassword plugin. Fire a callback function if the password passes the test or if it fails the tests. | |
* @param expressions Object with a key => value pair of label => regex expression. | |
* @param success_callback Function the callback to fire when the user passes all of the tests. | |
* @param error_callback Function the callback to fire when the user fails any of the tests. | |
* @return Object | |
* | |
* Example: http://jsfiddle.net/WXqUZ/5/ | |
* $('input[type=password]').validatePassword({ | |
* 'Uppercase': /([A-Z]+)/, | |
* 'Lowercase': /([a-z]+)/, | |
* 'Number': /([0-9]+)/ | |
* }, function() { | |
* alert('All tests passed!'); | |
* }, function() { | |
* console.log('Password is not strong enough.'); | |
* }); | |
*/ | |
$.fn.validatePassword = function(expressions, success_callback, error_callback) { | |
var self = $(this), | |
object_size = Object.keys(expressions).length, | |
li_width = ($('body').width() / object_size) - (2 * object_size), | |
password_checks, expr, html, indicator; | |
html = '<ul id="password-checks">'; | |
for(var i in expressions) { | |
if(!expressions.hasOwnProperty(i)) { | |
continue; | |
} | |
expr = expressions[i]; | |
html += '<li style="width: '+ li_width +'px">'; | |
html += '<span class="check-label">'+ i +'</span>'; | |
html += '<div id="indicator_'+ i +'" class="check-indicator"></div>'; | |
html += '</li>'; | |
} | |
html += '</ul>'; | |
self.after(html); | |
self.keyup(function() { | |
for(var i in expressions) { | |
expr = expressions[i]; | |
indicator = $('#indicator_'+ i); | |
if(expr.test(self.val())) { | |
indicator.addClass('ok'); | |
} else { | |
indicator.removeClass('ok'); | |
} | |
} | |
if($('.ok').length == $('.check-indicator').length) { | |
success_callback(); | |
} else { | |
error_callback(); | |
} | |
}); | |
return self; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment