user3366906
user3366906

Reputation: 149

XSD validation for continous digits

I have below element where i do not want continuation of more than 3 digits any where in the string. How can i do that using pattern or any other way. Thanks.

e.g John - Valid, 123 John- Valid, 123John - valid, 1230John - Invalid , Jo1284hn - Invalid , John1734 - Invalid

<xs:element name="FirstName" nillable="true" minOccurs="0">
<xs:simpleType>
    <xs:restriction base="xs:string">           
        <xs:maxLength value="28"/>
        <xs:whiteSpace value="collapse"/>
    </xs:restriction>
</xs:simpleType>

Upvotes: 1

Views: 51

Answers (1)

sergioFC
sergioFC

Reputation: 6016

In XSD 1.1 you can use assertions

<xs:element name="FirstName" nillable="true" minOccurs="0">
    <xs:simpleType>
        <xs:restriction base="xs:string">           
            <xs:maxLength value="28"/>
            <xs:whiteSpace value="collapse"/>
            <xs:assertion test="not(matches($value, '\d{4}'))"/>
        </xs:restriction>
    </xs:simpleType>
</xs:element>

But you can do it even in XSD 1.0 using xs:pattern:

<xs:element name="FirstName" nillable="true" minOccurs="0">
    <xs:simpleType>
        <xs:restriction base="xs:string">           
            <xs:maxLength value="28"/>
            <xs:whiteSpace value="collapse"/>
            <xs:pattern value="\d{0,3}(\D+\d{0,3})*|(\d{0,3}\D+)+"/>
        </xs:restriction>
    </xs:simpleType>
</xs:element>

Or if you prefer it, you can separate the patterns:

<xs:element name="FirstName" nillable="true" minOccurs="0">
    <xs:simpleType>
        <xs:restriction base="xs:string">           
            <xs:maxLength value="28"/>
            <xs:whiteSpace value="collapse"/>
            <!-- Matches every strings (optionally starting with 0 to 3 digits) and optionally followed by [(non digits) + (0 to 3 digits)] n times -->
            <xs:pattern value="\d{0,3}(\D+\d{0,3})*"/>
            <!-- Matches every strings ending with a non-digit and not containing more than 3 continuous digits -->
            <xs:pattern value="(\d{0,3}\D+)+"/>
        </xs:restriction>
    </xs:simpleType>
</xs:element>

Upvotes: 1

Related Questions