Reputation:
Please can some one give me regular expression for password with the following rules.
Password should be at least 7 characters long. It should contain minimum 3 digits and one alphabetic character. Password can accept numbers, alphabets, special characters any number of times except numbers should be minimum 3.
Upvotes: 0
Views: 1817
Reputation: 3963
You can check complexity with regex pretty easily, but its not an end all...
Good article on setting up the different complexities you are looking for:
http://www.zorched.net/2009/05/08/password-strength-validation-with-regular-expressions/
You also might want to run the password against a simple dictionary, to see if it can be bypassed by a dictionary attack.
Upvotes: 0
Reputation: 180777
That said, there are some people out there who actually do it with regular expressions (although they too admit that it's complicated)
http://www.breakingpar.com/bkp/home.nsf/0/87256B280015193F87256C4F005D3717
Upvotes: 1
Reputation: 131676
Regular expressions aren't particularly good at ensuring that particular groups of characters appear a certain number of times. While it's probably possible - it would no doubt be convoluted and non-obvious.
If you're programming in .NET (C# or VB) you can use a simple validation function something like:
bool ValidatePasswordCompliance( string password )
{
int countDigits = 0;
int countAlpha = 0;
int countOthers = 0;
foreach( char c in password )
{
countDigit += c.IsDigit ? 1 : 0;
countAlpha += c.IsAlpha ? 1 : 0;
countOther += !(c.IsAlpha || c.IsDigit) ? 1 : 0;
}
return countDigits >= 3 && (countDigits + countAlpha + countOthers) >= 7;
}
If you're working with .NET 3.5 or higher, you could use LINQ to simplify this:
bool ValidatePasswordCompliance( string password )
{
return password.Count() >= 7 &&
password.Count( x => x.IsDigit ) >= 3;
}
Upvotes: 8
Reputation: 881263
Regular expressions, while elegant if done right, are not fit for all purposes. I would suggest that this is one of the cases it is not suited for.
Don't get me wrong, you can do it with a single RE, but it's likely to be far more complex and hard to maintain than some simple procedural which checks the length and character classes.
Upvotes: 2
Reputation: 179994
This is better suited to a validation function that checks your individual criteria one-by-one than an overly complicated regex.
If you're hellbent on using a regex, take a look at this almost identical question... but read the highest voted answer, not just the accepted one.
Upvotes: 4