In this post, we will see how to validate a password in java.
Here are rules for password:
- Must have at least one numeric character
- Must have at least one lowercase character
- Must have at least one uppercase character
- Must have at least one special symbol among
@#$%
- Password length should be between 8 and 20
Table of Contents [hide]
Using regex
Here is standard regex for validating password.
Here is explanation for above regex
^
asserts position at start of a lineGroup
(?=.*\\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
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
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?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.