1

Need help with regex for password validation in c#

  1. minimun length of 8 caracters and maximun of 16
  2. at least one digit, lower case and one uppper case

What i tired:

var rule = new Regex("^(?=.{8,16}(?=*[a-z])(?=.*[A-Z])(?=.*[0-9])$");

but it doesnt work :(

dee-see
  • 23,668
  • 5
  • 58
  • 91
Lynct
  • 201
  • 1
  • 4
  • 10
  • 9
    WHY DO YOU HAVE A MAX LENGTH. Stop it. Stop. – Phill Oct 17 '14 at 14:44
  • 2
    Does it have to be in a single regex? Why not just do each validation individually since it will be much easier to do and probably more readable (since your validation rules will be obvious from code if they are all individual). – Chris Oct 17 '14 at 14:45
  • 1
    @Phill: Because the field in the database where it is being stored plaintext has a length limit on it? ;-) – Chris Oct 17 '14 at 14:46
  • I think you just need to loose the ^ and $ tags. The way you have it now, it has to end with both a digit and a capital letter. – Greg Miller Oct 17 '14 at 14:46
  • @Chris, The field in the database should be a hash, not the password – Greg Miller Oct 17 '14 at 14:47
  • I don't think restricting password is a right way, you don't need to set a maximum length. – Terabyte Oct 17 '14 at 14:47
  • Nothing here requires that you use a regular expression. Why not just check the length and use Linq to test of one of each of the character types you want? – juharr Oct 17 '14 at 14:48
  • I wanted to practice regex =p – Lynct Oct 17 '14 at 14:48
  • IWannaHaveAPa$$prhaseWithLotsOfCharacterzAndWayBetter3ntropyThanAny+ingElz – Corak Oct 17 '14 at 14:49
  • 4
    @GregMiller: Dude! I included a smiley and everything! You are of course right for the benefit of all other readers that the database should only ever have a hash. – Chris Oct 17 '14 at 14:49
  • Why not simply do string.length greater than 7 ? You can add in the string.length less than 17 also to make sure it is between 8 and 16 for length. – deathismyfriend Oct 17 '14 at 14:50
  • 1
    @Lynct Please note that regular expressions are often slower than using equivalent string methods and can be confusing to programmers that are not familiar with them. In general if you don't need them, don't use them, but if you do need them, document them. – juharr Oct 17 '14 at 14:52
  • Why you people stop a person from learning regexes? – Avinash Raj Oct 17 '14 at 14:54
  • @AvinashRaj No ones stopping him from learning regular expressions, we don't want him to force short passwords, and by limiting the length of passwords it often suggests that the user is storing them as clear text. – Phill Oct 17 '14 at 14:55
  • @Phill i replied to `juharr's` comment.. i agree with your comment.. – Avinash Raj Oct 17 '14 at 14:56
  • Possible duplicate of [Reference - Password Validation](https://stackoverflow.com/questions/48345922/reference-password-validation) – ctwheels May 30 '18 at 15:35

3 Answers3

3

You forget to put closing paranthesis in the first lookahead. And also you need to add .* after all the lookaheads because lookrounds are zero width assertions, it won't match any character but only assert whether a match is possible or not.

var rule = new Regex(@"^(?=.{8,16}$)(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[0-9]).*$");

DEMO

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
  • still getting an exception.. System.ArgumentException: parsing "^(?=.{8,16}$)(?=*?[a-z])(?=.*?[A-Z])(?=.*?[0-9]).*$" - Quantifier {x,y} following nothing. – Lynct Oct 17 '14 at 14:55
  • ya i tried, is it possible the problem is with the "{}" when we define the length? – Lynct Oct 17 '14 at 15:40
0

I like to avoid Regex when I can. I'd do some simple tests:

 if (password.Length < 8 || password.Length > 16)
     result =  "Invalid Length";
 else if (!password.Any(char.IsDigit))
     result =  "Needs a digit";
 else if (!password.Any(char.IsLower))
     result =  "Needs a lowercase";
 else if (!password.Any(char.IsUpper))
     result =  "Needs an uppercase";
 else
     result = "Good password"; 

Simple, clean, and readable. Also you can also provide specific feedback to the user

Jonesopolis
  • 25,034
  • 12
  • 68
  • 112
0

This is an Advanced method which return the output error message clearly .

private bool ValidatePassword(string password, out string ErrorMessage)
{
    var input = password;
    ErrorMessage = string.Empty;

    if (string.IsNullOrWhiteSpace(input))
    {
        throw new Exception("Password should not be empty");
    }

    var hasNumber = new Regex(@"[0-9]+");
    var hasUpperChar = new Regex(@"[A-Z]+");
    var hasMiniMaxChars = new Regex(@".{8,15}");
    var hasLowerChar = new Regex(@"[a-z]+");
    var hasSymbols = new Regex(@"[!@#$%^&*()_+=\[{\]};:<>|./?,-]");

    if (!hasLowerChar.IsMatch(input))
    {
        ErrorMessage = "Password should contain At least one lower case letter";
        return false;
    }
    else if (!hasUpperChar.IsMatch(input))
    {
        ErrorMessage = "Password should contain At least one upper case letter";
        return false;
    }
    else if (!hasMiniMaxChars.IsMatch(input))
    {
        ErrorMessage = "Password should not be less than or greater than 12 characters";
        return false;
    }
    else if (!hasNumber.IsMatch(input))
    {
        ErrorMessage = "Password should contain At least one numeric value";
        return false;
    }

    else if (!hasSymbols.IsMatch(input))
    {
        ErrorMessage = "Password should contain At least one special case characters";
        return false;
    }
    else
    {
        return true;
    }
}
Anurag
  • 557
  • 6
  • 14