XForms/Validate with schema types

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Motivation[edit | edit source]

You would like to use a library of XML Schema simple types with restrictions to validate your form.

Notice[edit | edit source]

Most type validation with the exception of the most simple types does not currently work under the FireFox extension.

Sample Program sample.xhtml[edit | edit source]

<?xml version="1.0" encoding="UTF-8"?>
      <title>Validate Postal Codes</title>
      <style type="text/css">
         @namespace xf url("http://www.w3.org/2002/xforms");
         xf|input {
            display: table-row;
            line-height: 2em;

         xf|label {
            display: table-cell;
            text-align: right;
            font-family: Arial, Helvetica, sans-serif;;
            font-weight: bold;
            padding-right: 5px;
            width: 150px;

         *:required {
             background-color: yellow;

         *:invalid  {
            background-color: pink;
      <xf:model schema="schema.xsd">
         <xf:instance src="instance.xml" />
         <xf:bind id="zip" required="true()" type="ftype:zipType" nodeset="ftype:zip" />
         <xf:bind id="zip2" required="true()" type="ftype:zip2Type" nodeset="ftype:zip2" />
      <xf:input bind="zip" incremental="true">
         <xf:label>Zip Code: </xf:label>
         <xf:hint>Validation is not correctly specified for this field</xf:hint>
         <xf:alert>The 'Zip Code' failed to validate!</xf:alert>
      <xf:input bind="zip2" incremental="true">
         <xf:label>Zip Code 2: </xf:label>
         <xf:hint>Validation is correctly specified for this field</xf:hint>
           <xf:output value="concat('The &amp;quot;', name(), '&amp;quot; failed to validate!')" />

Example XML Schema File schema.xsd[edit | edit source]

<?xml version="1.0" encoding="UTF-8"?>
 elementFormDefault="qualified" attributeFormDefault="unqualified">
   <xs:element name="data">
         <xs:documentation>Test XML Schema</xs:documentation>
            <xs:element name="zip" type="ftype:zipType"/>
   <xs:simpleType name="zipType">
      <xs:restriction base="xs:string">
         <!-- bad pattern: matches any sequence of 5 digits, even if there are more digits or non-numeric. -->
         <xs:pattern value="\d{5}"/>
   <xs:simpleType name="zip2Type">
      <xs:restriction base="xs:string">
         <!-- good pattern: matches only 5 digits, nothing extra -->
         <xs:pattern value="^\d{5}$"/>

Sample instance document instance.xml[edit | edit source]

<?xml version="1.0" encoding="UTF-8"?>
<data xmlns="http://www.example.com/my-file-types">

Discussion[edit | edit source]

Next Page: Facet Validation | Previous Page: Validate
Home: XForms