Password validation with certain conditions

14 / Jun / 2010 by Amit Jain 0 comments

Hi Friends,

I needed to validate password for certain conditions. As per the requirements, any valid must password must pass the following conditions:

  1. Minimum of 7 characters
  2. Must have numbers and letters
  3. Must have at least a one special characters- “!,@,#,$,%,&,*,(,),+”

I wrote the following method to meet the requirements:

import java.util.regex.*

boolean validatePassword(String password) {
   def pattern = /^.*(?=.{7,})(?=.*\d)(?=.*[a-zA-Z])(?=.*[!@#$%*&+()]).*$/
    def matcher = password =~ pattern
    return matcher.getCount() ? true : false
}

I couldn’t make the single regular expression to make it work, so used two. If somebody knows better way of doing it the please share.

Thanks to Imran for helping me in writing the regular expression.

Hope this helped!
~~Amit Jain~~
amit@intelligrape.com

http://www.tothenew.com

FOUND THIS USEFUL? SHARE IT

Leave a comment -