Monday, January 24, 2022

Password validation in java

 How to validate a Password using Regular Expressions in Java ?

A password is considered valid password if it contains all the following constraints.

  • It must have at least 8 characters and at most 20 characters.
  • It must have at least one digit.
  • It must have at least one upper case alphabet.
  • It must have at least one lower case alphabet.
  • It must have at least one special character like !@#$%&*()-+=^.
  • It doesn’t contain any white space.
Regular expression for password validation.
regex = “^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&-+=()])(?=\\S+$).{8, 20}$”
Explain on by one:
  • ^ represents starting character of the string.
  • (?=.*[0-9]) represents at least one digit(0 to 9).
  • (?=.*[a-z]) represents at least one lower case alphabet.
  • (?=.*[A-Z]) represents at least an upper case alphabet.
  • (?=.*[@#$%^&-+=()] represents at least one special character.
  • (?=\\S+$) represents, white spaces don’t allowed in the string.
  • .{8, 20} check  the length of string must be between 8 to 20
  • $ represents the end of the string.
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PasswordValidationTest {

	public static void main(String[] args) {
		String stringPass = "Test@1235";
		if (!isValidPassword(stringPass)) {
			System.out.println("Password validation successfully.");
		} else {
			// do code here after valid password
			System.out.println("Password valid successfully.");
		}
	}

	public static boolean isValidPassword(String password) {
		String regex = "^(?=.*[0-9])" + "(?=.*[a-z])(?=.*[A-Z])" + "(?=.*[@#$%^&+=])" + "(?=\\S+$).{8,20}$";
		Pattern p = Pattern.compile(regex);
		// return false if empty
		if (password == null) {
			return false;
		}
		Matcher m = p.matcher(password);
		return m.matches();
	}
}
Output:
Password validation successfully.