PrimeFaces 不提供开箱即用的功能。
然而,使用字符数组上的简单 for 循环将掩码模式转换为正则表达式模式应该是相对简单的。然后,您可以使用此正则表达式模式来验证该值。
例如
<p:inputMask ... validator="maskValidator">
和
@FacesValidator("maskValidator")
public class MaskValidator implements Validator {
@Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
String submittedValue = context.getExternalContext().getRequestParameterMap().get(component.getClientId(context));
if (submittedValue == null || submittedValue.isEmpty()) {
return; // Let @NotNull / required="true" handle.
}
InputMask input = (InputMask) component;
String mask = input.getMask();
StringBuilder regex = new StringBuilder();
for (char c : mask.toCharArray()) {
switch (c) {
case 'a': regex.append("[a-zA-Z]"); break;
case '9': regex.append("[0-9]"); break;
case '?': case '+': case '*': regex.append(c); break;
default: regex.append(Pattern.quote(Character.toString(c))); break;
}
}
if (!submittedValue.matches(regex.toString())) {
throw new ValidatorException(new FacesMessage(submittedValue + " does not match " + mask));
}
}
}
请注意,验证器使用未转换的提交值,而不是传入的第三个参数,它可能预先(隐式)转换,因此可能具有不同的toString()
表示形式。