Passay - Pesan yang Disesuaikan

Pustaka passay menyediakan MessageResolver API untuk mengganti pesan default yang digunakan oleh validator. Ini dapat mengambil jalur ke file properti khusus dan menggunakan kunci standar untuk mengganti pesan yang diperlukan.

Contoh

Contoh di bawah ini menunjukkan validasi kata sandi dan menampilkan pesan khusus menggunakan pustaka Passay.

messages.properties

INSUFFICIENT_UPPERCASE=Password missing at least %1$s uppercase characters.
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));            
      }
   }
}

Keluaran

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