[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Regular Expressions checking password strength check and email format

Posted on 2009-04-03
12
Medium Priority
?
1,154 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
ID: 24064940
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 85

Expert Comment

by:ozo
ID: 24065583
\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
ID: 24065634
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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 9

Expert Comment

by:ghostdog74
ID: 24065969
>> 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
ID: 24066327
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
ID: 24066738
>> 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
 
LVL 9

Expert Comment

by:ghostdog74
ID: 24066746
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
ID: 24075757
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
ID: 24075872
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
ID: 24076877
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 2000 total points
ID: 24076918
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
ID: 24085114
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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I have been reconstructing a PHP-based application that has grown into a full blown interface system over the last ten years by a developer that has now gone into business for himself building websites. I am not incredibly fond of writing PHP code o…
The purpose of this article is to demonstrate how we can use conditional statements using Python.
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.
This video teaches viewers about errors in exception handling.
Suggested Courses
Course of the Month17 days, 21 hours left to enroll

830 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