0

All,

I am using ASP.NET MVC and trying to do a Regular Expression to enforce Password requirements.

Register.cshtml:

@Html.ValidationMessageFor(model => model.Passwd, "", new {@class = "text-danger"})

Model Class:

    [RegularExpression("/(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).{8}/g", 
         ErrorMessage = "Password must meet requirements")]
    public string Passwd { get; set; }

I copied out the RegEx and tested it standalone in RegexPal.com and it worked perfectly.

However, when using it in my ASP.NET MVC app, I get the error message every time (even using Passwords that I know meet the requirements.

Am I doing something wrong? Does the DataAttributes RegularExpression Attribute behave differently than standard RegEx?

Philip Tenn
  • 6,003
  • 8
  • 48
  • 85
  • [This](http://stackoverflow.com/questions/8244572/dataannotations-validation-regular-expression-in-asp-net-mvc-4-razor-view) post might guide you to some extent. – Nikhil Vartak May 12 '17 at 03:46

1 Answers1

8

You could try the following

   [RegularExpression(@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8}$", 
         ErrorMessage = "Password must meet requirements")]
    public string Passwd { get; set; }

If you also want to require at least one special character, try this:

   [RegularExpression(@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\da-zA-Z]).{8}$", 
         ErrorMessage = "Password must meet requirements")]
    public string Passwd { get; set; }  
Trung Duong
  • 3,475
  • 2
  • 8
  • 9