Checking whether the password have whitespaces or not

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

Sometimes user chooses a password that will have whitespaces.

If you want to restrict user from creating a password that does have whitespaces, you can use “WhitespaceRule” class.

“WhitespaceRule” class makes sure that the password set by the user doesn’t have whitespaces.

Below is the complete main code for your reference.

Main class

1  package defaultPackage;
2  
3  import org.passay.PasswordData;
4  import org.passay.PasswordValidator;
5  import org.passay.RuleResult;
6  import org.passay.WhitespaceRule;
7  
8  public class Example15 {
9      public static void main(String[] args) {
10         WhitespaceRule whitespaceRule = new WhitespaceRule();
11         PasswordValidator passwordValidator = new PasswordValidator(whitespaceRule);
12         
13         String password = "packard_124";
14         PasswordData passwordData = new PasswordData(password);
15         RuleResult ruleResult = passwordValidator.validate(passwordData);
16         System.out.println("Result of password validation: " + ruleResult.isValid());
17         System.out.println("--------------------------------------");
18         
19         password = "packard 124";
20         passwordData = new PasswordData(password);
21         ruleResult = passwordValidator.validate(passwordData);
22         System.out.println("Result of password validation: " + ruleResult.isValid());
23         System.out.println("--------------------------------------");
24     }
25 }

In the above code, at line 10, I created an instance of “WhitespaceRule” class.

At line 11, I created an instance of “PasswordValidator” and passed the instance of “WhitespaceRule” as a constructor argument.

At line 13, I created a password and validated it at line 15 by calling the “validate” method of “PasswordValidator” class.

Since this password doesn’t have any whitespaces, the result will be true.

At line 19, I created another password which has whitespaces and validated it at line 21 by calling the “validate” method of “PasswordValidator” class.

Since this password has whitespaces, the result will be false.

In this way, we can use “WhitespaceRule” class to verify whether the password contains whitespaces or not.

Leave a comment