20

Note: This question, I believe, is not the duplicate of this question. My question is dealing with the default validation rules asp.net core identity has for password validation and how it's regex can be made, while the linked question is discussing, in general about act of validating password (which doesn't solve my problem)

The ASP.NET Core enables default following password validation

  1. Minimum 8 characters
  2. Should have at least one number
  3. Should have at least one upper case
  4. Should have at least one lower case
  5. Should have at least one special character (Which special characters are allowed?)

Keeping these conditions in mind I tried making the following regex but it is not working.

^((?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])|(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[^a-zA-Z0-9])|(?=.*?[A-Z])(?=.*?[0-9])(?=.*?[^a-zA-Z0-9])|(?=.*?[a-z])(?=.*?[0-9])(?=.*?[^a-zA-Z0-9])).{8,}$

This regex is accepting the strings even when either of three conditions from points 2,3,4,5 matches. But I want that all conditions should satisfy.

What am I doing wrong here?

Karan Desai
  • 3,012
  • 5
  • 32
  • 66
  • Please be specific when you say "it is not working". For which input does it fail? – CodeFuller Feb 06 '18 at 05:02
  • @CodeFuller Updated – Karan Desai Feb 06 '18 at 05:06
  • 3
    Your assumptions are *not* correct. The password rules are configured through [`PasswordOptions`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.identity.passwordoptions) and the defaults are a length of 6, one unique character, at least one non-alphanumeric, one lowercase, one uppercase, and one digit. – The rules being configurable, it does make little sense to have this as a regular expression. Why do you want this as a regular expression? – poke Feb 06 '18 at 08:23
  • 4
    I want this to be handled at client side. So in input I will validate at client side as well. – Karan Desai Feb 06 '18 at 10:15

1 Answers1

40

so, use

^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[#$^+=!*()@%&]).{8,}$
  • ^: first line
  • (?=.*[a-z]) : Should have at least one lower case
  • (?=.*[A-Z]) : Should have at least one upper case
  • (?=.*\d) : Should have at least one number
  • (?=.*[#$^+=!*()@%&] ) : Should have at least one special character
  • .{8,} : Minimum 8 characters
  • $ : end line

for more information: this

MD. Khairul Basar
  • 4,976
  • 14
  • 41
  • 59
Mohammad Javad Noori
  • 1,187
  • 12
  • 23
  • 7
    More recent versions of ASP.NET Core do not limit special characters, so anything that is not a Latin letter or digit is a special character. The correct regex should be: `^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^a-zA-Z\d]).{8,}$` Source: https://github.com/aspnet/AspNetIdentity/blob/b7826741279450c58b230ece98bd04b4815beabf/src/Microsoft.AspNet.Identity.Core/PasswordValidator.cs#L58 – arni Apr 10 '21 at 15:22