Solved

Regular Expressions checking password strength check and email format

Posted on 2009-04-03
12
1,143 Views
Last Modified: 2012-05-06
I am looking for a couple of regular expressions which checks the password strength which has maximum of 8 characters, alphanumeric, upper and lower case.

And a separate one for checking the email format of a string which conforms to email format specs and also check that the domain matches a particular patter i.e. checking test@123.com contains @123.com
0
Comment
Question by:indy28
  • 5
  • 3
  • 3
  • +1
12 Comments
 
LVL 13

Expert Comment

by:numberkruncher
Comment Utility
A regular expression which checks for at least 8 characters of alphanumeric characters (but a minimum of 3) of upper and lower case would be something like the following:

^[A-Za-z0-9]{3,8}$

Then to make sure that a password contains a minimum number of any of those you can use separate regular expressions. If the programming language that you are using supports the compilation of regular expressions, then I would strongly recommend flagging these for compilation. See the source code block below for a rough example of how to do this.

As for email address, the following website has the regex that you need (http://www.regular-expressions.info/regexbuddy/email.html):

\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b

// Example written in C#:
 

bool ValidatePassword(string input)

{

   if (Regex.IsMatch(input, "^[A-Z0-9]{3,8}$", RegexOptions.Compiled | RegexOptions.IgnoreCase))

   {

      // Password contains valid characters, check strength of password!
 

      // Find out how many characters are upper, lower, and numeric.

      int totalUpper = Regex.Matches(input, "[A-Z]", RegexOptions.Compiled).Count;

      int totalLower = Regex.Matches(input, "[a-z]", RegexOptions.Compiled).Count;

      int totalNumeric = Regex.Matches(input, "\\d", RegexOptions.Compiled).Count;
 
 

      // For this example, there must be at least 1 upper, 1 lower, and 2 numeric.

      if (totalUpper < 1)

      {

         // Display error message.

         Console.Write("There must be at least one upper case letter!");

         return false;

      }

      if (totalLower < 1)

      {

         // Display error message.

         Console.Write("There must be at least one lowercase letter!");

         return false;

      }

      if (totalNumeric < 2)

      {

         // Display error message.

         Console.Write("There must be at least two numeric characters!");

         return false;

      }
 

      // Success!!

      return true;

   }
 

   // Failed, didn't even match first rule!

   Console.Write("Password contains one or more invalid characters.");

   return false;

}
 
 

// Implementation Example:
 

string input = "pAssw0rd";
 

if (ValidatePassword(input))

{

   // Password is valid!

}

else

{

   // Password is invalid!

}

Open in new window

0
 
LVL 84

Expert Comment

by:ozo
Comment Utility
\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b
fails to match
The Fred and Barney Comedy Team <fred&barney@stonehenge.com>

^[A-Za-z0-9]{3,8}$
checks for no more than 8, not at least 8 characters
0
 
LVL 13

Expert Comment

by:numberkruncher
Comment Utility
The proper email address validation regex (according to the referenced source: http://www.regular-expressions.info/email.html) is listed in the source box below.

Unless I am misunderstanding something here, the question requests a regex which constrains the password to a maximum of 8 characters.
(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])

Open in new window

0
 
LVL 9

Expert Comment

by:ghostdog74
Comment Utility
>> checks the password strength which has maximum of 8 characters
depending on what programming language you are using, it might have functions for checking string length. eg in Python

if len(string) > 3 and len(string <=8 ) ......

>>  alphanumeric

if string.isalnum() : ......

>> uppercase, lowercase

1 in map(str.isupper,list(string)) or 1 in map(str.islower,list(string))

>> user@email.com

check for "@" in the string. split the string, on "@" , check for exactly 2 elements. etc etc..

No need regular expression.
0
 
LVL 13

Expert Comment

by:numberkruncher
Comment Utility
Regular expressions make it much simpler to count how many upper, lower, and numeric characters there are. This makes it very simple to determine the strength of a password. Regular expressions are very efficient, especially when compiled. I cannot see a reason in a case like this why you would try to avoid using them. After all, this is the kind of stuff that they are designed for.

Simply checking for an "@" in a string does not verify whether or not an email address is valid. There are other factors involved, which is why the official regex for this is so long. There is a shorter alternative that can be used which matches most cases (but not all) which is also available from the same link if size is for some reason a problem. Personally I would stick to the more accurate one.
0
 
LVL 9

Expert Comment

by:ghostdog74
Comment Utility
>> I cannot see a reason in a case like this why you would try to avoid using them
1) hard to read, debug if there are troubles
2) takes some time to develop and test, especially when one is not familiar.

as for checking of email, if this is my project, i would simply just check for @ and then test the email using a service that can actually send a test mail to the recipient and getting a response back, then i can consider it valid. No need regular expression.



0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 9

Expert Comment

by:ghostdog74
Comment Utility
i am not saying regex is bad or something, i am just providing another alternative that  may appear easier to comprehend than regex. ( After all, if OP has no trouble with regex, he wouldn't post in the first place.)
0
 

Author Comment

by:indy28
Comment Utility
Thanks a lot for the comments guys, lots of useful stuff.  I have had some more clarification from the client regarding what checks they need: Apologies as this is a bit different to what I initially posted:

1. They require a password which is a minimum 8 characters length and at least 1 alphabetic letter and at least 1 number and at least 1 uppercase letter and at least 1 lowercase letter. Hope that makes sense!

2. The regex that was posted verified the format of an email just fine thanks but i am also  looking for a regex which matches the domain part of the email to a specific pattern as well as doing the usual format checking.For example I want to match all emails which contain '@123.com' so 'test@123.com' would pass but 'test@124.com' would not.

Thanks in advance for your help
0
 
LVL 13

Expert Comment

by:numberkruncher
Comment Utility
For #1 there is only a small change to the password checking (source #1).

For #2 your requirement is even more efficient as you can remove half of the regex. Just take a look at source #2 below.

Let me know how you get on.
SOURCE #1 - The password bit

============================
 

// Example written in C#:

 

bool ValidatePassword(string input)

{

   if (Regex.IsMatch(input, "^[A-Z0-9]{3,8}$", RegexOptions.Compiled | RegexOptions.IgnoreCase))

   {

      // Password contains valid characters, check strength of password!

 

      // Find out how many characters are upper, lower, and numeric.

      int totalUpper = Regex.Matches(input, "[A-Z]", RegexOptions.Compiled).Count;

      int totalLower = Regex.Matches(input, "[a-z]", RegexOptions.Compiled).Count;

      int totalNumeric = Regex.Matches(input, "\\d", RegexOptions.Compiled).Count;

 

 

      // For this example, there must be at least 1 upper, 1 lower, and 2 numeric.

      if (totalUpper == 1 && totalLower == 1 && totalNumeric == 1)

      {

         // Success!

         return true;

      }

      else

      {

         // Failed, must be at least 1 upper, lower and numeric.

         Console.Write("Password must contain at least 1 upper, lower, and numeric character.");

         return false;

      }

   }

 

   // Failed, didn't even match first rule!

   Console.Write("Password contains one or more invalid characters.");

   return false;

}

 

 

// Implementation Example:

 

string input = "pAssw0rd";

 

if (ValidatePassword(input))

{

   // Password is valid!

}

else

{

   // Password is invalid!

}
 
 

SOURCE #2 - The email bit

=========================
 

// In the following pattern just change 123\.com to what you want. Be sure to escape all .'s  as  \.
 

string emailPattern = @"(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|""(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*"")@123\.com";
 

if (Regex.IsMatch(email, emailPattern, RegexOptions.Compiled | RegexOptions.IgnoreCase))

{

    // Valid Email!

}

else

{

    // Invalid Email!

}

Open in new window

0
 

Author Comment

by:indy28
Comment Utility
Hi numberkruncher

I am using a RegularExpression Validation control in ASP.NET to do the actual validation in both counts and thus there is no program as set out in your code samples, but they do help in figuring out what is going on.  Will the regular expressions you have provided work like this?  I tried the following password AbcD12345 with the expression you supplied but it didn't pass it, just to reiterate we are looking for an expression which will validate a MINIMUM 8 character length password

Regards
0
 
LVL 13

Accepted Solution

by:
numberkruncher earned 500 total points
Comment Utility
Okay, change the password regex to the following:   ^[A-Za-z0-9]{8,}$

It is a little better suited to the regular expression validation control in ASP.NET.

Sorry, I forgot to make the minimum of 8 change in my last post.

For the more advanced logic you will need to write some additional server-side logic on your "Submit" button (or the like). Are you using some sort of submit button?
0
 

Author Comment

by:indy28
Comment Utility
I ended up using the customvalidator validator control and used your server side method as a basis for checking the password. It all seems to work and is being accepted by the client so thanks for that!
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
no14 challenge 14 56
What regex will remove duplicate rel="nofolow" tags? 3 79
changeXy challenge 13 56
firstChar challenge 13 83
As most anyone who uses or has come across them can attest to, regular expressions (regex) are a complicated bit of magic. Packed so succinctly within their cryptic syntax lies a great deal of power. It's not the "take over the world" kind of power,…
How to remove superseded packages in windows w60 or w61 installation media (.wim) or online system to prevent unnecessary space. w60 means Windows Vista or Windows Server 2008. w61 means Windows 7 or Windows Server 2008 R2. There are various …
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now