XSD 验证可选字符串且只有 4 个数字

XSD validation optional string and only 4 numbers

我需要在此 XSD 中进行验证。 FD 是可选的。 如果你填写FD它应该只有4个数字(不是2个数字或5个数字)

                    <xs:element name="FD" minOccurs="0" maxOccurs="1" nillable="false">
                      <xs:annotation>
                        <xs:documentation>FD-code optional only 4 numbers</xs:documentation>
                      </xs:annotation>
                      <xs:simpleType>
                        <xs:restriction base="xs:string">
                          <xs:length value="4" fixed="true"/>
                          <xs:pattern value="[0-9][0-9][0-9][0-9]"/>
                        </xs:restriction>
                      </xs:simpleType>
                    </xs:element>

目前,xsd 拒绝空值。

问题: 我如何让它接受一个空值,如果它确实包含填充的东西,它只包含四位数字?

所以: 空的好 1位数字错误 2位数字是错误的 3个数字是错误的 4位数是正确的 5位数字错误 字母错误

问题可能是您使用的是长度而不是 maxLength。此外,您使用的模式需要 4 个数字,而不是 0-4 个数字。

试试这个:

<xs:element name="FD" minOccurs="0" maxOccurs="1" nillable="false">
    <xs:annotation>
        <xs:documentation>FD-code optional only 4 numbers</xs:documentation>
    </xs:annotation>
    <xs:simpleType>
        <xs:restriction base="xs:string">
            <xs:maxLength value="4"/>
            <xs:pattern value="([0-9]{4})?"/>
        </xs:restriction>
    </xs:simpleType>
</xs:element>