< XForms

Motivation

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

Method

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 Image


Example of error on bind

Sample Code


   <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>
This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.