In this post under Passay, I will show with example how to verify that the password is of specified length.
Below is the complete code for your reference
Main class
1 package defaultPackage;
2
3 import org.passay.LengthRule;
4 import org.passay.PasswordData;
5 import org.passay.PasswordValidator;
6 import org.passay.Rule;
7 import org.passay.RuleResult;
8
9 public class Example3 {
10 public static void main(String[] args) {
11 Rule lengthRule = new LengthRule(8);
12 PasswordValidator passwordValidator = new PasswordValidator(lengthRule);
13
14 String data = "hello";
15 System.out.println("First test '" + data + "'");
16 PasswordData passwordData = new PasswordData(data);
17 RuleResult ruleResult = passwordValidator.validate(passwordData);
18 System.out.println("Result of password validation: " + ruleResult.isValid());
19 System.out.println("--------------------------------------");
20
21 data = "hello1234";
22 System.out.println("Second test '" + data + "'");
23 passwordData = new PasswordData(data);
24 ruleResult = passwordValidator.validate(passwordData);
25 System.out.println("Result of password validation: " + ruleResult.isValid());
26 System.out.println("--------------------------------------");
27
28 data = "hello123";
29 System.out.println("Third test '" + data + "'");
30 passwordData = new PasswordData(data);
31 ruleResult = passwordValidator.validate(passwordData);
32 System.out.println("Result of password validation: " + ruleResult.isValid());
33 System.out.println("--------------------------------------");
34 }
35 }
In the above code, at line 11, I create a rule which says password length should be exactly of 8 characters not more and not less.
At line 12, I create a “PasswordValidator” instance passing the rule as a parameter.
From line 14 to 33, I perform 3 tests where for first test, I enter a password of length less than 8, for second test I will enter a password of length more than 8, and for third and last test I
enter password of length equals to 8.
The first two tests will fail where as the third test will pass.
Below is the output for your reference.
Output
First test 'hello'
Result of password validation: false
--------------------------------------
Second test 'hello1234'
Result of password validation: false
--------------------------------------
Third test 'hello123'
Result of password validation: true
--------------------------------------
In this way we can verify that the password is specified of length.