IllegalRegexRule example

In this post under Passay, I will explain with example the purpose of “IllegalRegexRule” class.

In one of my previous post, I have explained with example the purpose of “AllowedRegexRule” class.

We will have recap of it here. When validating password, we mainly check whether the password follows a particular pattern. If the password follows the pattern it is valid or else invalid.

We use regular expressions, to create that pattern.

“AllowedRegexRule” class will do the job of checking the user entered password against that pattern. If the password follows the pattern it is valid or else invalid.

“IllegalRegexRule” is opposite of “AllowedRegexRule”.

Here we create a pattern and check whether the password follow a particular pattern or not. If the password follows the pattern the password is invalid or else valid.

All we have to do is when creating an instance of “IllegalRegexRule” class, we pass the regular expression as constructor argument.

Below is the main class showing how to use the “IllegalRegexRule” class

Main class

1  package defaultPackage;
2  
3  import org.passay.IllegalRegexRule;
4  import org.passay.PasswordData;
5  import org.passay.PasswordValidator;
6  import org.passay.RuleResult;
7  
8  public class Example18 {
9      public static void main(String[] args) {
10         IllegalRegexRule illegalRegexRule = new IllegalRegexRule("[\\w\\d]*\\_qwerty\\_[\\w\\d]*");
11         PasswordValidator passwordValidator = new PasswordValidator(illegalRegexRule);
12         
13         PasswordData passwordData = new PasswordData("aaabbb");
14         RuleResult ruleResult = passwordValidator.validate(passwordData);
15         System.out.println(ruleResult.isValid());
16         
17         passwordData = new PasswordData("abc_qwerty_90");
18         ruleResult = passwordValidator.validate(passwordData);
19         System.out.println(ruleResult.isValid());
20     
21         passwordData = new PasswordData("90_abc");
22         ruleResult = passwordValidator.validate(passwordData);
23         System.out.println(ruleResult.isValid());
24     }
25 }

For our example I have used the below regular expression

[\\w\\d]*\\_qwerty\\_[\\w\\d]*

This regular expression creates a pattern which will match successfully with the passwords that have “qwerty” text as a substring.

All the password that follow this pattern are invalid and others that doesn’t follow the pattern are valid.

In the above code, at line 10, I create an instance of “IllegalRegexRule” class and pass the pattern as constructor arguments.

At line 11, we create an instance of “PasswordValidator” class and pass the instance of “IllegalRegexRule” as an constructor arguments.

Once we obtain the instance of “PasswordValidator”, we call its “validate” method and pass the user entered password as method argument. This method will decide whether the passed password is valid or not.

In this way we can use “IllegalRegexRule” class.

Leave a comment