How to use regular expressions validate format, range and length in schemas

J.D. Meier, Jason Taylor, Prashant Bansode, Carlos Farre, Madhu Sundararajan, Steve Gregersen.

Use regular expressions in schemas to validate format, range or length. This will allow you to use complex validation logic without need for implementing the code. Also it will allow decoupling the validation logic from the business logic. The example schema below exemplifies the validation of integer with values of between 1 and 5, the string of length 5 and social security number and zip code with good formats.
<?xml version="1.0" encoding="utf-8"?>
<xs:schema elementFormDefault="qualified" targetNamespace="http://Microsoft.PatternPractices.WCFGuide" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://Microsoft.PatternPractices.WCFGuide">
  <xs:element name="GetData">
    <xs:complexType>
      <xs:sequence>
        <xs:element minOccurs="1" name="CustomerInfo" nillable="false" type="tns:CustomerData" />
      </xs:sequence>
    </xs:complexType>
  </xs:element>
  <xs:complexType name="CustomerData">
    <xs:sequence>
      <xs:element name="CustomerID" type="tns:CustIDLimitor">
      </xs:element>
      <xs:element name="text" type="tns:CustomerN">
      </xs:element>
      <xs:element name="socialSecurity" type="tns:SSN">
      </xs:element>     
      <xs:element name="custZipCode" type="tns:CustomerN">
      </xs:element>          
    </xs:sequence>
  </xs:complexType>
  <xs:simpleType name="CustomerN">
    <xs:restriction base="xs:string">
      <xs:minLength value="1" />
      <xs:maxLength value="5" />
    </xs:restriction>
  </xs:simpleType>
  <xs:simpleType name="CustIDLimitor">
    <xs:restriction base="xs:int">
      <xs:minInclusive value="1" />
      <xs:maxInclusive value="5" />
    </xs:restriction>
  </xs:simpleType>
  <xs:simpleType name="SSN">
    <xs:restriction base="xs:token">
      <xs:pattern value="[0-9]{3}-[0-9]{2}-[0-9]{4}"/>
    </xs:restriction>
  </xs:simpleType>
  <xs:simpleType name="us-zipcode">
    <xs:restriction base="xs:string">
      <xs:pattern value="[0-9]{5}(-[0-9]{4})?"/>
    </xs:restriction>
  </xs:simpleType>
  <xs:element name="GetDataResponse">
    <xs:complexType>
      <xs:sequence>
        <xs:element minOccurs="1" name="GetDataResult" nillable="false" type="tns:CustomerData" />
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

Last edited May 8, 2008 at 6:25 AM by prashantbansode, version 1

Comments

No comments yet.