In this post under Passay, I will show with example what is the purpose and how to use “DictionaryRule”.
DictionaryRule will check whether the user inputed password matches a word amoung a dictionary of words. If it matches, the validation fails or else passes.
The dictionary of words can be implemented in many ways but for this example I will be using “WordListDictionary” provided by Passay itself.
Below is the complete main class for your reference.
Main class
package defaultPackage;
import java.util.Arrays;
import org.passay.DictionaryRule;
import org.passay.PasswordData;
import org.passay.PasswordValidator;
import org.passay.RuleResult;
import org.passay.dictionary.ArrayWordList;
import org.passay.dictionary.WordList;
import org.passay.dictionary.WordListDictionary;
public class Example27 {
public static void main(String[] args) {
String[] words = new String[] {"Lantern", "Meadow", "Glacier", "Whisper", "Compass", "Orchard", "Velvet", "Horizon"};
Arrays.sort(words);
WordList wordList = new ArrayWordList(words);
WordListDictionary wordListDictionary = new WordListDictionary(wordList);
DictionaryRule dictionaryRule = new DictionaryRule(wordListDictionary);
PasswordValidator passwordValidator = new PasswordValidator(dictionaryRule);
PasswordData passwordData = new PasswordData("Lantern");
RuleResult result = passwordValidator.validate(passwordData);
System.out.println("Validation result for 'Lantern': " + result.isValid());
passwordData = new PasswordData("abc1998dfjasdfjaoe");
result = passwordValidator.validate(passwordData);
System.out.println("Validation result for 'abc1998dfjasdfjaoe': " + result.isValid());
}
}
In the above code at line 15, I create an array of words and at line 16 I sort them. Sorting them is important.
At line 17 I created an instance of “WordList” named “wordList” from the array of words as constructor argument.
At line 19, I created an instance of “WordListDictionary” named “wordListDictionary” using the “wordList” as constructor argument
At line 21, I created an instance of “DictionaryRule” named “dictionaryRule” using the “wordListDictionary” as constructor argument.
At line 22, I created an instance of “PasswordValidator” named “passwordValidator” using “dictionaryRule” as constructor argument.
At line 24 and 28, I used two passwords and validated them at line 25 and 29, and print there results at line 26 and 30.
Below is the output
Output
Validation result for 'Lantern': false
Validation result for 'abc1998dfjasdfjaoe': true
From the output you can see ‘Lantern’ is part of the dictionary and as a result validation failed, whereas ‘abc1998dfjasdfjaoe’ was not part of the dictionary and it passed.
In this way we can use ‘DictionaryRule’ class