HOWTO: Use Regex's to Validate Email Addresses and Passwords

| No TrackBacks
I recently came across some decent regular expressions (regex's) to validate email addresses, and check password complexity.  They are as follows:

To validate an email address:

^[_a-z0-9-]+(\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,4})$

To validate a password for basic complexity:

^\\w*(?=\\w*\\d)(?=\\w*[a-z])(?=\\w*[A-Z])\\w*$

The password complexity regex verifies that the password String contains at least 1 number, at least 1 lower case letter, and at least one upper case letter.  In addition to Java, I've used these regular expressions in JavaScript and PHP.  They work well for most needs.  Continue reading for code samples.
In Java ... RegexTester.java

if ( !email.matches("^[_a-z0-9-]+(\\.[_a-z0-9-]+)*@[a-z0-9-]+" +
                                "(\\.[a-z0-9-]+)*(\\.[a-z]{2,4})$") ) {
    throw new Exception( "Error, bad email address." );
}

... and ...

if ( !password.matches("^\\w*(?=\\w*\\d)(?=\\w*[a-z])(?=\\w*[A-Z])\\w*$") ||
                password.length() < 8 ) {
    throw new Exception( "Error, bad password or password not complex enough." );
}

For PHP, I've used the code available from the Feedback Form Wizard.  The PHP function check_email is also available here.

Did You Find this Helpful?

Did you find this post helpful, or at least, interesting?

  

Send Mark a Direct Message

If you'd like to send me a direct message, please do so below. However, I do not publicly post comments or messages submitted directly to me. So, if you're going to try to SPAM me, or my blog, you're pretty much wasting your time.

400 characters remaining

Error

About Mark

A Silicon Valley native, Mark Kolich is a full-time Software Engineer, a casual entrepreneur, and a consultant for hire. A web technologies expert, his current focus is on building powerful and robust cloud-driven web-applications using Java, PHP, Perl, AJAX, DHTML, CSS, and JavaScript. His favorite programming languages are PHP, Java and JavaScript. He uses Linux, enjoys biking to work, loves building great software, and always writes elegant, readable, and maintainable code.

No TrackBacks

No trackbacks attached to this entry.

Twitter (@markkolich)

Translate

About this Entry

This page contains a single entry by Mark Kolich published on October 28, 2008 10:31 AM.

Michael Crichton: Environmentalism, Reality or Fantasy? was the previous entry in this blog.

HOWTO: Hide Apache Server Version for Security using ServerTokens and ServerSignature is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.