Reputation: 1364
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 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 :
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.
Upvotes: 1
Views: 977
Reputation: 626748
The problems with the code are:
/g
modifier used in a regex that is later used in RegExp#test()
(see this SO post)Also, note that checking the length of a string is better done with a regular string length check method:
$('#newPassword').keyup(function(e) {
var strongRegex = /^(?=.*\d)(?=.*[!@@#$%^&*]+)(?![.\n])(?=.*[A-Z])(?=.*[a-z]).{8,}$/;
// Use the literal regex notation so as not to double escape \ symbols! Else,
// var strongRegex = RegExp("^(?=.*\\d)(?=.*[!@@#$%^&*]+)(?![.\n])(?=.*[A-Z])(?=.*[a-z]).{8,}$");
if ($(this).val().length < 8) { // no need in the enoughRegex
$('#passstrength').html('More Characters');
}
else if (strongRegex.test($(this).val())) {
$('#passstrength').html('Meet Our Password Policy!');
}
else {
$('#passstrength').html('Please insert a strong password!');
}
return true;
});
Upvotes: 1