Hibernate validator constraints in XML

故事扮演 提交于 2019-12-14 04:22:27

问题


I am using xml file to specify my constraints on an incoming request bean. I do this in a validation-constraints.xml file as follows:

<?xml version="1.0" encoding="UTF-8"?>
<constraint-mappings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://jboss.org/xml/ns/javax/validation/mapping validation-mapping-1.0.xsd"
    xmlns="http://jboss.org/xml/ns/javax/validation/mapping">
    <default-package>com.mathworks.internal.business.geoTypes
    </default-package>

    <bean class="GetStatesByCountryCodeRequest">
        <field name="countryCode">
            <constraint annotation="org.hibernate.validator.constraints.NotBlank" />

        </field>
    </bean>

</constraint-mappings>

I also need the countryCode to be only 2 characters long. I looked at the length validator provided by hibernate but it requires a min and a max value which I am guessing in my case should be 2 and 2. How can I specify the length constraint in a XML way? I cannot find any examples for that.


回答1:


I ended up doing the following:

<bean class="GetStatesByCountryCodeRequest">
        <field name="countryCode">
            <constraint annotation="org.hibernate.validator.constraints.NotBlank" />
            <constraint annotation="org.hibernate.validator.constraints.Length">
                <element name="min">2</element>
                <element name="max">2</element>
            </constraint>

        </field>
    </bean>

This seems to have fixed the problem for now.




回答2:


To solve your issue the Pattern Constraint would be better I think.

<constraint annotation="javax.validation.constraints.Pattern" >
    <element name="regexp">[a-zA-Z]{2}</element>
</constraint>

This would define a length 2 string.

Instead of the violation message "size must be between 2 and 2"
you would have "must match "[a-zA-Z]{2}""



来源:https://stackoverflow.com/questions/21528464/hibernate-validator-constraints-in-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!