Last modified on 24 March 2011, at 18:27

XForms/Validation with Bind

MotivationEdit

You want to validate a single field based on a rule and alert the user if they enter an invalid value.

MethodEdit

We will use an XForms bind expression:

  <xf:bind nodeset="PositiveDecimalAmount" 
      type="xs:decimal" 
      constraint=". > 0"/>

This last line says that if the current element is greater than zero then the rule passes and the field is valid.

Screen ImageEdit

Example of error on bind

Sample CodeEdit

   <html
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:xf="http://www.w3.org/2002/xforms" 
    xmlns:xs="http://www.w3.org/2001/XMLSchema" 
    >
    <head>
        <title>Validation With Bind</title>
        <style type="text/css">
        <![CDATA[
            body {
            font-family: Helvetica, sans-serif;
            }
        ]]>
        </style>
        <xf:model>
            <xf:instance xmlns="">
               <data>
                    <PositiveDecimalAmount>1.0</PositiveDecimalAmount>
                    <NegativeDecimalAmount>-1.0</NegativeDecimalAmount>
                </data>
            </xf:instance>
 
            <!-- note that the gt operator does not work and that the greater than character must be escaped.  -->
            <xf:bind nodeset="PositiveDecimalAmount" type="xs:decimal" required="false()" constraint=". &gt; 0"/>
 
            <!-- note that the lt operator does not work and that the less than character must be escaped.  -->
            <xf:bind nodeset="NegativeDecimalAmount" type="xs:decimal" required="false()" constraint=". &lt; 0"/>
 
 
        </xf:model>
    </head>
    <body>
        <h1>Validation With Bind</h1>
        <p>To pass this test the form must warn the user if they enter </p>
 
            <xf:input class="PositiveDecimalAmount" ref="PositiveDecimalAmount" incremental="true">
                <xf:label>Positive Decimal Amount:</xf:label>
                <xf:alert>Amount must be a positive decimal number.</xf:alert>
            </xf:input>
            <br/>
            <xf:input class="NegativeDecimalAmount" ref="NegativeDecimalAmount" incremental="true">
                <xf:label>Negative Decimal Amount:</xf:label>
                <xf:alert>Amount must be a negative decimal number.</xf:alert>
            </xf:input>
            <br/>
    </body>
</html>

Next Page: Case Validation | Previous Page: Load

Home: XForms