Code, JavaEE

Regular Expression Java – Validate Password

Validate a password using regular expressions.

</pre>
public class PasswordRegExTest {
 private Logger LOG = LoggerFactory.getLogger(PasswordRegExTest.class);

private static final String REG_EX_PWD =
 "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[\p{Punct}]).{8,64})";
 private Pattern pattern;
 private Matcher matcher;

@Test
 public void testValidatePasswordUsingRegEx() {
 List<String> passwordsList = new LinkedList<>();
 passwordsList.add("Uz2@ThisWEFnl9");
 passwordsList.add("uZ9uzaej$");
 passwordsList.add("Uz2@");
 passwordsList.add("uZ9uzaej");
 passwordsList.add("Ik4#Ploy");
 passwordsList.add("12345678");

for (String pwd : passwordsList) {
 validatePassword(pwd, matcher);
 }
 }

private void validatePassword(String pwd, Matcher matcher) {
 matcher = pattern.matcher(pwd);
 if (matcher.matches()) {
 LOG.info("Password -> {} is VALID.", pwd);
 } else {
 LOG.info("Password -> {} is NOT VALID.", pwd);
 }
 }

@Before
 public void setUp() {
 pattern = Pattern.compile(REG_EX_PWD);
 }

@After
 public void tearDown() {
 pattern = null;
 matcher = null;
 }
}
<pre>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s