带消息的Hibernate约束映射验证器

时间:2017-01-06 06:07:49

标签: java hibernate-validator

这是validation.xml

<constraint-mappings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xsi:schemaLocation="http://jboss.org/xml/ns/javax/validation/mapping validation-mapping-1.1.xsd"
                 xmlns="http://jboss.org/xml/ns/javax/validation/mapping" version="1.1">
<default-package>com.esq.rbac.model</default-package>
<bean class="Tenant" ignore-annotations="true">
    ...
    <field name="ivrPin">
        <constraint annotation="javax.validation.constraints.Size">
            <element name="min">6</element>
            <element name="max">6</element>
            <message>IVR Pin must be 6 digit numeric</message>
        </constraint>
        <constraint annotation="javax.validation.constraints.Pattern">
            <element name="regexp">[0-9]+</element>
        </constraint>
    </field>
</bean>

执行期间收到错误说

c.e.u.imports.Main [run] - HV000115: Error parsing mapping file.
javax.validation.ValidationException: HV000115: Error parsing mapping file.
Caused by: org.xml.sax.SAXParseException: cvc-complex-type.2.4.a: 
Invalid content was found starting with element 'message'. One of '{"http://jboss.org/xml/ns/javax/validation/mapping":element}' is expected.
at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)

如何正确包含错误消息

1 个答案:

答案 0 :(得分:3)

您只需在message代码之后constraint annotation代码后直接放置element即可进行一项更改。

<bean class="Tenant" ignore-annotations="true">
...
<field name="ivrPin">
    <constraint annotation="javax.validation.constraints.Size">
        <message>IVR Pin must be 6 digit numeric</message>
        <element name="min">6</element>
        <element name="max">6</element>

    </constraint>

原因如下:

如果你看一下xsd文件进行验证 - 映射:

<强>验证映射-1.1.xsd

<xs:complexType name="constraintType">
    <xs:sequence>
        <xs:element type="xs:string" name="message" minOccurs="0"/>
        <xs:element type="map:groupsType"
                    name="groups"
                    minOccurs="0"/>
        <xs:element type="map:payloadType"
                    name="payload"
                    minOccurs="0"/>
        <xs:element type="map:elementType"
                    name="element"
                    maxOccurs="unbounded"
                    minOccurs="0"/>
    </xs:sequence>
    <xs:attribute type="xs:string" name="annotation" use="required"/>
</xs:complexType>

使用xs:sequence标记指定子元素必须出现在序列中。请参阅element sequence。此处 message 属性位于其他属性之前,如 groups payload element