Example: Validating User Input Via WMLScript
In the following example, we will build a simple WML card that asks the user to input a social security number (an identification number used by the U.S. Social Security Administration). We will then use WMLScript to verify that the user’s input was formatted correctly. Following this verification, we’ll alert the user via WMLScript to let them know whether their number was accepted or not. This example, though simple, represents a typical usage of WMLScript on a client.
To build this example, we create a normal WML file containing two cards: an input card and a results card (see Listing 1 below). Accepting the input will result in our validateSSN() function being called. Note that this function is stored in a separate .wmls file (WMLScriptExample.wmls) and is declared within that file using the extern keyword. extern allows a function to be called by other functions or WML events that exist outside of the function’s source file. To keep a function "private", simply declare the function without using the extern keyword.
Listing 1 - WMLScriptExample.wml
<?xml version='1.0'?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1//EN" "http://www.wapforum.org/DTD/wml_1.1.xml">
<wml>
<card id="SSN" title="SSN:">
<do type="accept" label="Results">
<go href="WMLScriptExample.wmls#validateSSN($(SSN))"/>
</do>
<p>
Enter SSN: <input type="text" name="SSN"/>
</p>
</card>
<card id="Results" title="Results:">
<p>
You entered:<br/>
SSN: $(SSN)<br/>
</p>
</card>
</wml>
Listing 2 - WMLScriptExample.wmls
extern function validateSSN(SSN)
{
if (String.length(SSN) != 9)
{
WMLBrowser.setVar("SSN", "Error: String must be 9 digits long.");
}
WMLBrowser.go("WMLScriptExample.wml#Results");
};

Figure 1
|

Figure 2
|
For more information on the WML code above, see our WML tutorial. The WMLScript function shown in Listing 2 makes use of two of the standard WMLScript libraries: WMLBrowser and String. The WMLBrowser.setVar() function sets the value of a WML variable while the WMLBrowser.go() function redirects execution of the script to a card within a WML source file.
WirelessDevNet Training Home