You can force user to set a strong password during the registration process or change password process. Now the question in what you understand with the word – “strong password”.
Basic definition of strong password is that it should contain:
- At least one uppercase character
- At least one lowercase character
- At lease one numeric character
- At least one special character
- Minimum n number of character (we will take n=8)
To achieve the same thing in code we need to do following steps:
1. Create a basic html page containing a password input type and a button.
Validate Password Field
Password:
Validate
2. Include jQuery library: There are two ways to do that
- You can download jQuery library from jQuery.com and include it yourself.
- You can include it from CDN ( Content Delivery Network ) like from Google and Microsoft.
We will going to use Google CDN
3. RegEx that will validate password which should contain uppercase, lowercase, numeric & special character. We will take minimum password length 8 and maximum 15.
/^(?=.*d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*s).{8,15}$/
4. Define a jQuery function to validate password
$(document).ready(function()
{
function passwordValidation()
{
if ($("#password").val().match(/^(?=.*d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*s).{8,15}$/))
{
$("#validationMsg").text("Password Looks Strong");
$("#validationMsg").css("color", "green");
}
else
{
$("#validationMsg").text("Password should contain uppercase, lowercase, numeric, special character and length limit is 8-15");
$("#validationMsg").css("color", "red");
}
}
});
Validate Password Field in jQuery Using RegEx
1. On Button Click
To call function on button click, we need to define jQuery click() method somewhere inside already defined ready() method.
$(document).ready(function()
{
//Funtion calling on button click using button id
$("#submitButton").click(function()
{
passwordValidation();
});
});
2. When Name Field Loses Focus
To call function when cursor leave the box, we need to define jQuery blur() method somewhere inside already defined ready() method.
$(document).ready(function()
{
//Funtion calling when cursor leave box using box id
$("#password").blur(function()
{
passwordValidation();
});
});
3. Validate While Key-Pressing
To call function while key-pressing, we need to define jQuery keyup() method somewhere inside already defined ready() method.
$(document).ready(function()
{
//Funtion calling while key-pressing using box id
$("#password").keyup(function()
{
passwordValidation();
});
});
If you have any question please feel free to ask in comments