Validate password in java

In this post, we will see how to validate a password in java.
Here are rules for password:

  1. Must have at least one numeric character
  2. Must have at least one lowercase character
  3. Must have at least one uppercase character
  4. Must have at least one special symbol among @#$%
  5. Password length should be between 8 and 20

Using regex

Here is standard regex for validating password.

Here is explanation for above regex

^ asserts position at start of a line
Group (?=.*\\d)
Assert that the Regex below matches
.* matches any character (except for line terminators)
\\ matches the character \ literally (case sensitive)
d matches the character d literally (case sensitive)
Group (?=.*[a-z])
Assert that the Regex below matches
.* matches any character (except for line terminators)
Match a single character present in the list below [a-z]
a-z a single character in the range between a (index 97) and z (index 122) (case sensitive)
Group (?=.*[A-Z])
Assert that the Regex below matches
.* matches any character (except for line terminators)
Match a single character present in the list below [A-Z]
A-Z a single character in the range between A (index 65) and Z (index 90) (case sensitive)
Group (?=.*[@#$%])
Assert that the Regex below matches
.* matches any character (except for line terminators)
Match a single character present in the list below [@#$%]
@#$% matches a single character in the list @#$% (case sensitive)
.{8,20} matches any character (except for line terminators)
{8,20} Quantifier — Matches between 8 and 20 times, as many times as possible, giving back as needed (greedy)
$ asserts position at the end of a line

Here is java program to implement it.

Output:

Java2blog@ is valid password:true
helloword#123 is valid password:false

Using String’s matches method

We can also use string’s matches() method to validate password in java.
Let’s see with the help of an example.

Output:

Java2blog@ is valid password:true
Password must have atleast one uppercase character
helloword#123 is valid password:false

That’s all about how to validate password in java.

Was this post helpful?

Leave a Reply

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