我创建了一个 bean 验证器,并将其应用于我的 bean setter 方法。我没有得到 JSF 验证错误,而是引发了异常。有没有办法让它工作,或者我应该使用传统的 JSF 验证器?
//Bean Method
public void setGuestPrimaryEmail(@ValidEmail String email){
guest.getEmails().get(0).setValue(email);
}
//Validator interface
@Target({ElementType.FIELD,ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = EmailValidator.class)
public @interface ValidEmail {
String message() default "{invalid}";
Class<? extends Payload>[] payload() default {};
Class<?>[] groups() default {};
}
//Validator impl
public class EmailValidator implements ConstraintValidator<ValidEmail, String> {
private Pattern p;
@Override
public void initialize(ValidEmail constraintAnnotation) {
p = java.util.regex.Pattern
.compile("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?");
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (DothatUtils.isEmpty(value)) {
return true;
}
boolean invalid = !p.matcher(value).matches();
if (invalid)
return false;
return true;
}
}
异常:
2013-11-30T20:58:41.747+0000|SEVERE: javax.faces.component.UpdateModelException:
javax.el.ELException: /index.xhtml @144,86 value="....":
javax.validation.ConstraintViolationException: 1 constraint violation(s) occurred during method validation.
注意:我将 GF4 与 JSF 2.2.4 一起使用。如果我将自定义注释放在字段上,它就会按预期工作。
最佳答案
ElementType.PARAMETER
无法被默认的 JSR303 bean 验证提供程序识别。
2.1 Constraint annotation
...
Constraint annotations can target any of the following
ElementType
s:
FIELD
for constrained attributesMETHOD
for constrained gettersTYPE
for constrained beansANNOTATION_TYPE
for constraints composing other constraintsWhile other
ElementType
s are not forbidden, the provider does not have to recognize and process constraints placed on such types. Built-in types do supportPARAMETER
andCONSTRUCTOR
to allow Bean Validation provider specific extensions. It is considered good practice to follow the same approach for custom annotations.
您确实必须将约束注释放在属性(由 ElementType.FIELD
标识)或 getter(由 ElementType.METHOD
标识)上。请注意,不支持受约束的 setter!
关于jsf - 如何在 JSF 2.2 中使用方法参数级别验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20305680/