My web application will generate the password on registration form. But user are allow to change password by it they want.
When user enter the password, it must follow our password policy.
Our password policy is :
- The password length must be greater than or equal to 8
- The password must contain one or more uppercase characters
- The password must contain one or more lowercase characters
- The password must contain one or more numeric values
- The password must contain one or more special characters
The regex is (?=^.{8,}$)(?=.\d)(?=.[.!@#$%^&]+)(?![.\n])(?=.[A-Z])(?=.[a-z]).$
This is my C# code to generate password :
Regex passPattern = new Regex("(?=^.{8,}$)(?=.*\\d)(?=.*[!@#$%^&*]+)(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$");
var password = System.Web.Security.Membership.GeneratePassword(10,2);
while (true)
{
if (!passPattern.IsMatch(password))
{
password = System.Web.Security.Membership.GeneratePassword(10, 2);
}
else
{
break;
}
}
It will loop and keep generate the password until it match.
On the form, I also validate the password policy by using Jquery. Here the code snippet :
<script type="text/javascript">
$('#newPassword').keyup(function(e) {
var strongRegex = new RegExp("(?=^.{8,}$)(?=.*\d)(?=.*[!@@#$%^&*]+)(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$", "g");
var enoughRegex = new RegExp("(?=.{8,}).*", "g");
if (false == enoughRegex.test($(this).val())) {
$('#passstrength').html('More Characters');
}
else if (strongRegex.test($(this).val())== true) {
$('#passstrength').html('Meet Our Password Policy!');
}
else {
$('#passstrength').html('Please insert strength password!');
}
return true;
});
So the result :
- A%rI_2{l#Y = Not match
- P@ssw0rd.123 = Match
- 2@C*DjDQdJ = Match
- ex@#XcINQ0 = Not Match
As you see, not all the password is match. All this value have been tested at regex101.com & regexpal.com and all the result is match.
So how can solved this problem?
p/s: I using razor engine in my page, so you can see double '@' on my regex in jquery.