This project is read-only.

Use Regular Expressions in Schemas to Validate Format, Range or Length

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

Consider using regular expressions in schemas to validate format, range or length. This will allow you to use complex validation logic without need for implementing the complex validation code. Also it will allow decoupling the validation logic from the business logic. Schema validation provides a way to create validation for data types using XML rules, for validity check in regards to format, length and type. It supports using regular expressions. Without regular expressions, complex validation code would be required.

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 valid formats.
<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="ssn" type="tns:SSN">
      </xs:element>
      <xs:element name="zip" type="tns:us-zipcode">
      </xs:element>
    </xs:sequence>
  </xs:complexType>
  <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: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: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 Jun 12, 2008 at 11:16 PM by prashantbansode, version 1

Comments

No comments yet.