Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strong password regex [duplicate]

Tags:

c#

regex

I need strong password validation regex

Special Characters - Not Allowed
Spaces - Not Allowed
Numeric Character - At least one character
At least one Capital Letter 
Minimum and Maximum Length of field - 6 to 12 Characters
Repetitive Characters - Allowed only two repetitive characters

my Regex is ^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s)(?=(?:(\w)(?!\1{2}))+).{6,12}$ but it ignores special characters (where to add?)

Please help!

like image 572
Maxim Avatar asked Jun 28 '10 08:06

Maxim


People also ask

What does ?= Mean in regex?

?= is a positive lookahead, a type of zero-width assertion. What it's saying is that the captured match must be followed by whatever is within the parentheses but that part isn't captured. Your example means the match needs to be followed by zero or more characters and then a digit (but again that part isn't captured).

What is the regex for special characters?

Special Regex Characters: These characters have special meaning in regex (to be discussed below): . , + , * , ? , ^ , $ , ( , ) , [ , ] , { , } , | , \ . Escape Sequences (\char): To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "."


1 Answers

Doesn't sound like a task particularly suited for Regex, since you want to test multiple conditions simultaneously. (You could use multiple regexes, but then normal C# with LINQ is a nicer way to test it.) Try the following function:

public static bool IsStrongPassword(string password)
{
    // Minimum and Maximum Length of field - 6 to 12 Characters
    if (password.Length < 6 || password.Length > 12)
        return false;

    // Special Characters - Not Allowed
    // Spaces - Not Allowed
    if (!(password.All(c => char.IsLetter(c) || char.IsDigit(c))))  
        return false;

    // Numeric Character - At least one character
    if (!password.Any(c => char.IsDigit(c)))
        return false;

    // At least one Capital Letter
    if (!password.Any(c => char.IsUpper(c)))
        return false;

    // Repetitive Characters - Allowed only two repetitive characters
    var repeatCount = 0;
    var lastChar = '\0';
    foreach(var c in password)
    {
        if (c == lastChar)
            repeatCount++;
        else
            repeatCount = 0;
        if (repeatCount == 2)
            return false;
        lastChar = c;
    }

    return true;
}

Make sure you import System.Linq of course, and you're set to go.

like image 110
Noldorin Avatar answered Sep 23 '22 15:09

Noldorin