Displaying meaningful error messages when password validation fails

In this post under Passay, I will show with example how to display error messages for failed password validation.

Below is the complete code for your reference.

Main class

1  package defaultPackage;
2
3 import java.util.List;
4 import java.util.Scanner;
5
6 import org.passay.LengthRule;
7 import org.passay.PasswordData;
8 import org.passay.PasswordValidator;
9 import org.passay.Rule;
10 import org.passay.RuleResult;
11
12 public class Example2 {
13 public static void main(String[] args) {
14 Rule lengthRule = new LengthRule(8, 16);
15 PasswordValidator passwordValidator = new PasswordValidator(lengthRule);
16 Scanner scanner = new Scanner(System.in);
17 System.out.println("Enter password");
18 String data = scanner.next();
19 PasswordData passwordData = new PasswordData(data);
20 RuleResult ruleResult = passwordValidator.validate(passwordData);
21 System.out.println("Result of password validation: " + ruleResult.isValid());
22 List<String> messages = passwordValidator.getMessages(ruleResult);
23 for(String message : messages) {
24 System.out.println(message);
25 }
26 }
27 }

In the above code, we take the password from the user and validate it. Refer to line 20.

The result of validation is stored in an instance of “RuleResult” class. Refer to line 20.

At line 22, we are getting the list of validation error messages by calling “getMessages” on “passwordValidator” instance and passing “ruleResult” instance as an argument. This will return a list of
type String.

From line 23 to 25, we go through the list of error messages and display them to the console.

In this way, we can get the error messages related to failed password validation.

Output

Enter password
hello
Result of password validation: false
Password must be 8 or more characters in length.

Leave a comment