| Flex 2 Developer's Guide > Flex Data Features > Storing Data > Using validators with a data model | |||
To validate the data stored in a data model, you use validators. In the following example, the <mx:EmailValidator>, <mx:PhoneNumberValidator>, <mx:ZipCodeValidator>, and <mx:SocialSecurityValidator> tags declare validators that validate the email, phone, zip, and ssn fields of the registration data model. The validators generate error messages when a user enters incorrect data in TextInput controls that are bound to the data model fields.
<?xml version="1.0"?>
<!-- Models\ModelTagEmptyString.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Model id="reg">
<registration>
<name>{username.text}</name>
<email>{email.text}</email>
<phone>{phone.text}</phone>
<zip>{zip.text}</zip>
<ssn>{ssn.text}</ssn>
</registration>
</mx:Model>
<mx:Validator required="true" source="{reg}" property="name"
trigger="{submit}" triggerEvent="click" listener="{username}"/>
<mx:EmailValidator source="{reg}" property="email"
trigger="{submit}" triggerEvent="click" listener="{email}"/>
<mx:PhoneNumberValidator source="{reg}" property="phone"
trigger="{submit}" triggerEvent="click" listener="{phone}"/>
<mx:ZipCodeValidator source="{reg}"
property="zip" trigger="{submit}" triggerEvent="click" listener="{zip}"/>
<mx:SocialSecurityValidator source="{reg}" property="ssn"
trigger="{submit}" triggerEvent="click" listener="{ssn}"/>
<!-- Form contains user input controls. -->
<mx:Form>
<mx:FormItem label="Name" required="true">
<mx:TextInput id="username" width="200"/>
</mx:FormItem>
<mx:FormItem label="Email" required="true">
<mx:TextInput id="email" width="200"/>
</mx:FormItem>
<mx:FormItem label="Phone" required="true">
<mx:TextInput id="phone" width="200"/>
</mx:FormItem>
<mx:FormItem label="Zip" required="true">
<mx:TextInput id="zip" width="60"/>
</mx:FormItem>
<mx:FormItem label="Social Security" required="true">
<mx:TextInput id="ssn" width="200"/>
</mx:FormItem>
<mx:FormItem>
<!-- User clicks Button to trigger validation. -->
<mx:Button id="submit" label="Validate"/>
</mx:FormItem>
</mx:Form>
</mx:Application>
This example cleanly separates the user interface and application-specific data. You could easily extend it to create a three-tier architecture by binding data from the registration data model into an RPC service request. You could also bind user input data directly into an RPC service request, which itself is a data model, as described in Using RPC Components.
For more information about validators, see Validating Data.
Flex 2.01