jsf - 如何在 JSF 2.2 中使用方法参数级别验证?

标签 jsf bean-validation jsf-2.2 java-ee-7

我创建了一个 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 验证提供程序识别。

来自JSR303 1.0 specification :

2.1 Constraint annotation

...

Constraint annotations can target any of the following ElementTypes:

  • FIELD for constrained attributes
  • METHOD for constrained getters
  • TYPE for constrained beans
  • ANNOTATION_TYPE for constraints composing other constraints

While other ElementTypes are not forbidden, the provider does not have to recognize and process constraints placed on such types. Built-in types do support PARAMETER and CONSTRUCTOR 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/

相关文章:

java - 我可以覆盖 jsr-303 验证注释吗

javascript - 更改事件时输入元素的样式边框

java - Richfaces:将附加参数传递给建议框的建议方法

java - 将表单提交到外部链接(但在这样做之前进行本地操作)

java - 如何在 Spring MVC 中使用自定义日期属性编辑器验证日期

java - jsr 303 验证数字并自动初始化为 0

jsf - 使用 JSF 2.2 时在每个回发请求上重新创建 @ViewScoped bean

image - 我们可以在 JSF 托管 bean 本身中基于 org.primefaces.model.UploadedFile 获取图像的高度和宽度吗?

jsf - 后端处理的进度条主要内容

jsf - 使用 JEE6 将 EJB 注入(inject) JSF 转换器