XSD schema: How to specify the number of digits in a value?

Ian Boyd picture Ian Boyd · Nov 19, 2010 · Viewed 15.9k times · Source

i want to limit the number of digits allowed in an element to 6:

<AccountNumber>123456</AccountNumber>
<AccountNumber>999999</AccountNumber>
<AccountNumber>000000</AccountNumber>

The field format specification is 6-digit, zero-padded, numeric.

i read that i might want to use the totalDigits restriction, based on:

totalDigits Specifies the exact number of digits allowed. Must be greater than zero

So i have the simple type:

<xs:simpleType name="AccountNumber">
   <xs:restriction base="xs:int">
      <xs:totalDigits value="6"/>
   </xs:restriction>
</xs:simpleType>

And while it catches invalid numbers, such as:

<AccountNumber>1234567</AccountNumber>
<AccountNumber>0000000</AccountNumber>
<AccountNumber></AccountNumber>

it doesn't catch invalid numbers:

<AccountNumber>12345</AccountNumber>
<AccountNumber>01234</AccountNumber>
<AccountNumber>00123</AccountNumber>
<AccountNumber>00012</AccountNumber>
<AccountNumber>00001</AccountNumber>
<AccountNumber>00000</AccountNumber>
<AccountNumber>0000</AccountNumber>
<AccountNumber>000</AccountNumber>
<AccountNumber>00</AccountNumber>
<AccountNumber>0</AccountNumber>

What is a suggested restriction to specify the exact number of digits allowed?

Answer

Jeff Yates picture Jeff Yates · Nov 19, 2010

You need to use xs:pattern and provide a regular expression to limit it to a number.

<xs:simpleType name="AccountNumber">
   <xs:restriction base="xs:int">
      <xs:pattern value="\d{6}"/>
   </xs:restriction>
</xs:simpleType>