Hibernate validator constraints in XML

2019-08-19 16:42发布

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.

2条回答
贼婆χ
2楼-- · 2019-08-19 17:21

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.

查看更多
我命由我不由天
3楼-- · 2019-08-19 17:21

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}""

查看更多
登录 后发表回答