Thursday, October 9, 2014

Lesson 31: How to generate and validate password on form

My task today is to validate password entered by user, and to add a button for generating random password based on some rule. This is the formula asked to be done by the Project Manager:
Password must be between 8-20 characters long and contains at least one number, one lower case letter, one upper case letter, one symbol, and cannot contain space in the middle of password.
There are 2 files that need to be modified. First we need to create a password validator file that will be used by the UserValidator.java. The content of PasswordValidator.java:
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PasswordValidator {
 private Pattern pattern;
 private Matcher matcher;

 private static final String PASSWORD_PATTERN = "((?=.*[a-z])(?=.*\\d)(?=.*[A-Z])(?=.*[@#$%!]).{8,40})";

 public PasswordValidator() {
  pattern = Pattern.compile(PASSWORD_PATTERN);
 }

 public boolean validate(final String password) {
  matcher = pattern.matcher(password);
  return matcher.matches();
 }
}
Thanks to Nikos Maravitsas for providing this java class.
In the UserValidator.java we only need to create new instance of PasswordValidator() and then call validate() function, the result will be either true or false.

That's for validating the password input by user, what if we want to provide the user with capability to generate some random password? we can also do that.
First you need this js function to be put in .jsp file:

function generatePassword(){
 //a random number between 8 and 20
 var len = Math.floor((Math.random() * 12) + 8);
 var text = "";

    var charset = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()-_=+";

    for( var i=0; i < len; i++ )
        text += charset.charAt(Math.floor(Math.random() * charset.length));

    document.getElementById('password').value = text;
    document.getElementById('repassword').value = text;     
}

and then we create a button like this for the user to click on:
<button onclick="generatePassword();return false;" class="button" >Generate password</button>

No comments:

Post a Comment