Passay - 定制消息


Passay 库提供了 MessageResolver API 来覆盖验证器使用的默认消息。它可以采用自定义属性文件的路径并使用标准来覆盖所需的消息。

例子

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

消息.属性

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));            
      }
   }
}

输出

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