Password Validation Program in Java

Hello everyone, in today’s tutorial I will be telling about how to do password validation in Java with simple code snippets using regular expression.

Below is the Java snippet for validation:

static final String REG =  "^(?=.*\\d)(?=\\S+$)(?=.*[@#$%^&+=])(?=.*[a-z])(?=.*[A-Z]).{8,10}$";

This all that is needed for mentioning our condition for the password.

Here,

  • (?=.*\\d) – at least 1 digit.
  • (?=\\S+$) – no white-space
  • (?=.*[@#$%^&+=]) – at least one special symbol (only the ones given within the [ ]).
  • (?=.*[a-z]) -at least one lower case letter.
  • (?=.*[A-Z]) – at least one upper case letter.
  • .{8,10} – minimum 8 and, maximum of 10 letters (can change to any convenient length).
  • $ – end of the string.
  • ^ – beginning of the string.

So REG should match all of the above criteria.

Static is used for the constant variable. FinalĀ  variable’s value can’t be modified

static final Pattern PATTERN = Pattern.compile(REG);

PATTERN.compileĀ  is a method of Pattern class in Java to match text against the regular expression more than once.

Below is code for the main section where we give a password and check if its matching our criteria of validation or not.

PATTERN.matcher is used to search operation on text for regular expression.

public static void main(String[] args)
  {
    String pass = "[email protected] 0218";

    if (PATTERN.matcher(pass).matches()) {
      System.out.print("The Password " + pass + " is valid");
    }
    else {
      System.out.print("The Password " + pass + " is invalid");
    }
  }

How to convert int to char in Java

The entire code snippet is :

{java.util.regex.Pattern – This the package for defining patterns.}

import java.util.regex.Pattern;
class Main
{
  
  static final String REG = "^(?=.*\\d)(?=\\S+$)(?=.*[@#$%^&+=])(?=.*[a-z])(?=.*[A-Z]).{8,10}$";

  private static final Pattern PATTERN = Pattern.compile(REG);

  public static void main(String[] args)
  {
    String pass = "[email protected]";

    if (PATTERN.matcher(pass).matches()) {
      System.out.print("The Password " + pass + " is valid"+"\n");
    }
    else {
      System.out.print("The Password " + pass + " is invalid"+"\n");
    }
  }
}

After running this code with content in the “pass” variable, it will print the statement in the output stating whether the password is valid or invalid.

And so one can change the value of the “pass” variable to check for a lot of variation to try and validate the password.

 

Output: Valid Password:

compile:
run:
The Password [email protected] is valid
BUILD SUCCESSFUL (total time: 1 second)

Password Validation Program in Java

Output: Invalid Password:

compile:
run:
The Password [email protected] 021 is invalid
BUILD SUCCESSFUL (total time: 1 second)

Password Validation Program in Java

I hope this tutorial was helpful to you. Thank you.

Leave a Reply

Your email address will not be published. Required fields are marked *