In this post under Passay, I will explain with example the purpose and how to use “IllegalCharacterRule” class.
In the previous, I explained the purpose of “AllowedCharacterRule” class.
The class “IllegalCharacterRule” is the opposite of “AllowedCharacterRule”.
In “AllowedCharacterRule” we create an array of characters that should be allowed in the password text. In other words a whitelist of characters.
In “IllegalCharacterRule” we create an array of characters that should not be allowed in the password text. In other words a blacklist of characters.
Below is the main class as example for your reference.
Main class
1 package defaultPackage;
2
3 import org.passay.IllegalCharacterRule;
4 import org.passay.PasswordData;
5 import org.passay.PasswordValidator;
6 import org.passay.RuleResult;
7
8 public class Example13 {
9 public static void main(String[] args) {
10 char[] blacklistCharacters = {'a', 'b', 'c', 'd', 'e', '1'};
11 IllegalCharacterRule illegalCharacterRule = new IllegalCharacterRule(blacklistCharacters);
12 PasswordValidator passwordValidator = new PasswordValidator(illegalCharacterRule);
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 = "wxyz";
21 passwordData = new PasswordData(data);
22 ruleResult = passwordValidator.validate(passwordData);
23 System.out.println("Result of password validation 'wxyz': " + ruleResult.isValid());
24 System.out.println("--------------------------------------");
25 }
26 }
In the above code, at line 10, I created an array of characters named “blacklistCharacters”, which shouldn’t be allowed in the password text.
At line 11, I created an instance of “IllegalCharacterRule” class named “illegalCharacterRule”.
At line 12, I created an instance of “PasswordValidator”.
At line 14, I created a password “abc1” which has only one character from the array “blacklistCharacters”.
When I verified the password at line 16, the validation fails.
At line 20, I created a password “wxyz” which doesn’t have any characters from the array “blacklistCharacters”.
When I verified the password at line 22, the validation is passed.
In this way we can use “IllegalCharacterRule”.
Below is the output for your reference.
Output
Result of password validation 'abc1': false
--------------------------------------
Result of password validation 'wxyz': true
--------------------------------------