Jquery validation on matching 'password' a

2019-07-22 04:36发布

This question already has an answer here:

I have tried to write a regular expression for passwords:

public class ApplicationUser : IdentityUser, ITimeStamps
{
    public const string PasswordRegularExpression = @"admin|password";
    // public const string PasswordRegularExpression = @"/admin|password/i"; // Tried this too
    // public const string PasswordRegularExpression = @"/(admin|password)/i"; // Tried this too

This is over and above the normal Microsoft identity stuff:

manager.PasswordValidator = new PasswordValidator
{
     RequiredLength = 6,
     RequireNonLetterOrDigit = false,
     RequireDigit = true,
     RequireLowercase = false,
     RequireUppercase = false,
};

Here's my Register view model:

public class RegisterViewModel
{
    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    [RegularExpression( ApplicationUser.PasswordRegularExpression, ErrorMessage = "The {0} must contain atleast 1 number and must not contain the word 'admin' or 'password'" )] 
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }
}

I am wanting to throw an error in jquery validation when someone uses password or admin inside their password. However, the jquery validation does not seem to be working as expected. What might I be missing?

The generated html from asp.net looks like this:

<input class="form-control input-validation-error" data-val="true" data-val-length="The Password must be at least 6 characters long." data-val-length-max="100" data-val-length-min="6" data-val-regex="The Password must contain atleast 1 number and must not contain the word 'admin' or 'password'" data-val-regex-pattern="admin|password" data-val-required="The Password field is required." id="Password" name="Password" placeholder="Enter a password" type="password">

Test cases:

  • I've added brackets, it still does not work as expected. I type in password and it actually does not fail! I then put 1 more character (doesn't matter what it is) and then it fails... and now I remove part of the word "password" so for example 'pasrd21234' and the error is still there!

Side notes:

1条回答
孤傲高冷的网名
2楼-- · 2019-07-22 05:05

Based upon the answer at Regular expression to match a line that doesn't contain a word?, the following regular expression should match any password except if it contains "admin" or "password":

^((?!(admin|password)).)*$

I've created a fiddle for this on Regex101 for testing prior to adding this into your application.

查看更多
登录 后发表回答