Passay 简明教程

Passay − Customized Messages

Passay库提供了一个MessageResolver API,用于覆盖验证程序使用的默认消息。它可以获取自定义属性文件的路径,并使用标准 keys 覆盖所需消息。

Example

以下示例显示了如何使用Passay库验证密码并显示自定义消息。

messages.properties

INSUFFICIENT_UPPERCASE=Password missing at least %1$s uppercase characters.

PassayExample.java

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.passay.CharacterRule;
import org.passay.EnglishCharacterData;
import org.passay.LengthRule;
import org.passay.MessageResolver;
import org.passay.PasswordData;
import org.passay.PasswordValidator;
import org.passay.PropertiesMessageResolver;
import org.passay.Rule;
import org.passay.RuleResult;
import org.passay.WhitespaceRule;

public class PassayExample {
   public static void main(String[] args) throws FileNotFoundException, IOException {
      List<Rule> rules = new ArrayList<>();
      rules.add(new LengthRule(8, 16));
      rules.add(new WhitespaceRule());
      rules.add(new CharacterRule(EnglishCharacterData.UpperCase, 1));
      rules.add(new CharacterRule(EnglishCharacterData.LowerCase, 1));
      rules.add(new CharacterRule(EnglishCharacterData.Digit, 1));
      rules.add(new CharacterRule(EnglishCharacterData.Special, 1));

      Properties props = new Properties();
      props.load(new FileInputStream("E:/Test/messages.properties"));
      MessageResolver resolver = new PropertiesMessageResolver(props);

      PasswordValidator validator = new PasswordValidator(resolver, rules);
      PasswordData password = new PasswordData("microsoft@123");
      RuleResult result = validator.validate(password);
      if(result.isValid()){
         System.out.println("Password validated.");
      }else{
         System.out.println("Invalid Password: " + validator.getMessages(result));
      }
   }
}

Output

Invalid Password: [Password missing at least 1 uppercase characters.]