< Day Day Up > |
If you have written any HTML forms, you likely have added client-side script to provide more responsive interaction with users than server-side scripting can provide, because the trip to the server to conduct validation is avoided when client-side scripting is used. Often client-side validation scripts in HTML forms are called only when the user attempts to submit the form data. In InfoPath 2003, the data source values, which are bound to form controls, can be validated in response to InfoPath validation events. To learn more about InfoPath validation events, see "Validation Events," p. 346 (Chapter 19). In this simple example, we will use script to specify that the last name must be the string "Smith" . Figure 10.7 shows the preview mode of the SimpleScript.xsn form template. Figure 10.7. The SimpleScript.xsn form template in preview mode.
We will use script to display an error message if text other than "Smith" is entered in the Last Name text box. Figure 10.8 shows the error message displayed. Figure 10.8. An error message created using JScript.
The JScript script, copied from the Microsoft Script Editor, is shown here: function msoxd_my_field2::OnAfterChange(eventObj) { // Write code here to restore the global state. if (eventObj.IsUndoRedo) { // An undo or redo operation has occurred and the DOM is read-only. return; } var LastName = XDocument.DOM.selectSingleNode("field2"); if (LastName != "Smith"){ XDocument.UI.Alert("The LastName field must consist of the string 'Smith'."); } } The name of the JScript function is created automatically by InfoPath. To create the functionality, follow these steps:
The first line of the code assigns the value of the field2 field (which we use to hold the last name) to the variable LastName . The right side of the assignment statement uses the XDocument object of the InfoPath object model. It has a DOM property, which represents the XML Document Object Model (DOM) of the data source. The XDocument object is automatically defined in the Microsoft Script Editor. We use the selectSingleNode() method of the DOM object to select the field2 field in the data source. The argument to the selectSingleNode() method is contained in paired double quotes, and is an XPath expression. In this case, the XPath expression is simply field2 , because the field2 node is a child node of the myFields node, which is the document element node of the document.
Script-based validation may be used alongside W3C XML Schema validation. Be sure that the constraints applied by the two techniques are not in conflict. |
< Day Day Up > |