How to validate the password by using regular expression in java

It is good to use regular expression to validate the password , rather than using validation functions . Regular expression is very easy and simple to modify .
Conditions to validate the password
(?=.*[A-Z])………: At least one capital alphabet .
(?=.*[a-z])………: At least one small alphabet .
(?=.*[\\d])……….: At least one number.
(?=.*[@$#%])..: At least one special character in @$#%.
(?!.*\\s)………. …: Not contain blank space .
.{6,17}……………: Length between 6 to 17 characters.
(?=.*[A-Z])(?=.*[a-z])(?=.*[\\d])(?=.*[@$#%])(?!.*\\s).{6,17}
Example to validate the password :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import java.util.regex.Pattern; import java.util.regex.Matcher; public class passwordValidation { public static void main(String[] args) { String password[] = new String[5]; password[0] = "P@ssw0rd";//valid password password[1] = "P@ssword";//no number password[2] = "Passw0rd";//no special character password[3] = "p@ssw0rd";//no capital alphabet password[4] = "password";//all small alphabets String regex = "(?=.*[A-Z])(?=.*[a-z])(?=.*[\\d])(?=.*[@$#%])(?!.*\\s).{6,17}"; Pattern pattern = Pattern.compile(regex); for(String passwordcheck : password) { Matcher match = pattern.matcher(passwordcheck); boolean status = match.matches(); System.out.println(passwordcheck+" validation is "+status); } } } |
Execution Result:
1 2 3 4 5 |
P@ssw0rd validation is true P@ssword validation is false Passw0rd validation is false p@ssw0rd validation is false password validation is false |
Returns true if the password satisfied all validations , false otherwise.
change {6,17} values to set password maximum and minimum length .
So these are the basic and common conditions to validate the password .

Related Posts : |
![]() |
How to validate email address by using regular expression in java |