AllowedRegexRule example

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

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.

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

Below is the main class showing how to use the class

Main class

1  package defaultPackage;
2  
3  import org.passay.AllowedRegexRule;
4  import org.passay.PasswordData;
5  import org.passay.PasswordValidator;
6  import org.passay.RuleResult;
7  
8  public class Example17 {
9      public static void main(String[] args) {
10         AllowedRegexRule allowedRegexRule = new AllowedRegexRule("[a-zA-Z]+\\_[0-9]+");
11         PasswordValidator passwordValidator = new PasswordValidator(allowedRegexRule);
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_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

[a-zA-Z]+\\_[0-9]+

This regular expression creates a pattern which indicates the password should start with alphabetic characters (lower or uppercase), followed by underscore “_” and ends with digits.

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

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

At line 11, we create an instance of “PasswordValidator” class and pass the instance of “AllowedRegexRule” 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 “AllowedRegexRule” class.

Leave a comment