为@Size提供自定义验证器

时间:2013-08-06 08:08:03

标签: java-ee-6 bean-validation

我如何为像@Size这样的内置约束提供自定义验证器实现?在JavaEE6 JSF Web应用程序中

1 个答案:

答案 0 :(得分:1)

实现ConstraintValidator<MyType, Size>,通过基于XML的约束映射注册它:

<constraint-mappings
    xmlns="http://jboss.org/xml/ns/javax/validation/mapping" version="1.1">

    <constraint-definition annotation="javax.validation.constraint.Size">
        <validated-by include-existing-validators="false">
            <value>org.mycompany.MySizeValidator</value>
        </validated-by>
    </constraint-definition>
</constraint-mappings>

并将此映射添加到META-INF/validation.xml

<validation-config
    xmlns="http://jboss.org/xml/ns/javax/validation/configuration" version="1.1">

    <constraint-mapping>path/to/mapping.xml</constraint-mapping>
</validation-config>

您可以在Hibernate Validator reference guide中了解更多信息。