While going through some of the examples in the Microsoft .NET Framework 3.5 – ASP.NET Application Development Self-Paced Training Kit, I came accross a nice Ajax component for evaluating the strength of password.
Add a JS file to the scripts folder and add this code:
/// Type.registerNamespace("AjaxEnabled"); //create constructor AjaxEnabled.PasswordStrengthComponent = function() { AjaxEnabled.PasswordStrengthComponent.initializeBase(this); } //define class AjaxEnabled.PasswordStrengthComponent.prototype = { initialize: function() { //add custom initialization here AjaxEnabled.PasswordStrengthComponent.callBaseMethod(this, 'initialize'); }, returnPasswordStrength: function(password) { var strPass = new String(password.toString()); if (strPass.length < 5) { return "Weak"; } else { if (strPass.length < 9) { return "Medium"; } else { return "Strong"; } } }, dispose: function() { //add custom dispose actions here AjaxEnabled.PasswordStrengthComponent.callBaseMethod(this, 'dispose'); } } //register class as a Sys.Component AjaxEnabled.PasswordStrengthComponent.registerClass( 'AjaxEnabled.PasswordStrengthComponent', Sys.Component); //notify script loaded if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();
Add reference to the JS in the page using the script manager:
<asp:ScriptManager ID="ScriptManager1" runat="server"> <Scripts> <asp:ScriptReference Path="~/AjaxComponent.js" /> </Scripts> </asp:ScriptManager>
Wire up the OnKeypress() event:
<script language="javascript" type="text/javascript"> function _OnKeypress() { var checker = new AjaxEnabled.PasswordStrengthComponent(); var pass = document.getElementById("txtPassword").value; var strength = checker.returnPasswordStrength(pass); document.getElementById("lblStrength").innerText = strength; } </script>