In this post under Passay, I will explain with example the purpose and how to use “AllowedCharacterRule” class.
When we ask a user to come up with a password, we can restrict them to use only those characters that are whitelisted by us.
In that case, we can have rule with the help of Passay’s “AllowedCharacterRule” class, that will make sure that the password entered by the user has only those characters.
Below is the main class giving an example of how to use the “AllowedCharacterRule” class for your reference.
Main class
1 package defaultPackage;
2
3 import org.passay.AllowedCharacterRule;
4 import org.passay.PasswordData;
5 import org.passay.PasswordValidator;
6 import org.passay.RuleResult;
7
8 public class Example12 {
9 public static void main(String[] args) {
10 char[] whitelistCharacters = {'a', 'b', 'c', 'd', 'e', '1'};
11 AllowedCharacterRule allowedCharacterRule = new AllowedCharacterRule(whitelistCharacters);
12 PasswordValidator passwordValidator = new PasswordValidator(allowedCharacterRule);
13
14 String data = "abc1";
15 PasswordData passwordData = new PasswordData(data);
16 RuleResult ruleResult = passwordValidator.validate(passwordData);
17 System.out.println("Result of password validation 'abc1': " + ruleResult.isValid());
18 System.out.println("--------------------------------------");
19
20 data = "wxyz1";
21 passwordData = new PasswordData(data);
22 ruleResult = passwordValidator.validate(passwordData);
23 System.out.println("Result of password validation 'wxyz1': " + ruleResult.isValid());
24 System.out.println("--------------------------------------");
25 }
26 }
In the above code, at line 10, I create an array of characters that should be present in the password. We name it as “whitelistCharacters”.
At line 11, I created an instance of “AllowedCharacterRule” class named “allowedCharacterRule” and pass the “whitelistCharacters” array as an constructor argument.
Next at line 12, I create an instance of “PasswordValidator” passing the “allowedCharacterRule” as a constructor argument.
At line 14, I created a password “abc1” which has only whitelisted characters. So when I test it at line 16, the verification passes.
At line 20, I created another password “wxyz1” which has only one whitelisted characters. So when I test it at line 22, the verification fails.
In this way we can use “AllowedCharacterRule” class
Below is the output
Output
Result of password validation 'abc1': true
--------------------------------------
Result of password validation 'wxyz1': false
--------------------------------------