You use the Flex data validation mechanism to validate the data in an application. Flex provides predefined validators for many common types of user-supplied data, such as date, number, and currency values.
The data that a user enters in a user interface might or might not be appropriate to the application. In Flex, you use a validator to ensure the values in the fields of an object meet certain criteria. For example, you can use a validator to ensure that a user enters a valid phone number value, to ensure that a String value is longer than a set minimum length, or ensure that a ZIP code field contains the correct number of digits.
In typical client-server environments, data validation occurs on the server after data is submitted to it from the client. One advantage of using Flex validators is that they execute on the client, which lets you validate input data before transmitting it to the server. By using Flex validators, you eliminate the need to transmit data to and receive error messages back from the server, which improves the overall responsiveness of your application.
Flex includes a set of validators for common types of user input data, including the following:
You often use Flex validators with data models. For more information about data models, see Storing data.
You define validators by using MXML or ActionScript. In MXML, you declare a validator in an <fx:Declarations> tag. You define validators in an <fx:Declarations> tag because they are not visual components.
For example, to declare the standard PhoneNumberValidator validator, you use the <mx:PhoneNumberValidator> tag, as the following example shows:
<?xml version="1.0"?>
<!-- validators\PNValidator.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Declarations>
<!-- Define the PhoneNumberValidator. -->
<mx:PhoneNumberValidator id="pnV"
source="{phoneInput}" property="text"/>
</fx:Declarations>
<!-- Define the TextInput control for entering the phone number. -->
<s:TextInput id="phoneInput"/>
<s:TextInput id="zipCodeInput"/>
</s:Application>
In the previous example, you enter a value into the TextInput control for the phone number. When you remove focus from the TextInput control by selecting the TextInput control for the ZIP code, the validator executes.
You use the source property of the validator to specify an object, and the property property to specify a field of the object to validate. For more information on the source and property properties, see About the source and property properties.
In the previous example, the validator ensures that the user enters a valid phone number in the TextInput control. A valid phone number contains at least 10 digits, plus additional formatting characters. For more information, see Validating phone numbers.
You declare validators in ActionScript either in a script block within an MXML file, or in an ActionScript file, as the following example shows:
<?xml version="1.0"?>
<!-- validators\PNValidatorAS.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Script>
<![CDATA[
// Import PhoneNumberValidator.
import mx.validators.PhoneNumberValidator;
// Create the validator.
private var v:PhoneNumberValidator = new PhoneNumberValidator();
private function createValidator():void {
// Configure the validator.
v.source = phoneInput;
v.property = "text";
}
]]>
</fx:Script>
<!-- Define the TextInput control for entering the phone number. -->
<s:TextInput id="phoneInput" creationComplete="createValidator();"/>
<s:TextInput id="zipCodeInput"/>
</s:Application>
Flex defines two sets of validators: Spark and MX. The Spark validators rely on the classes in the flash.globalization package. The flash.globalization classes use the locale data provided by the operating system. Therefore, Spark validators provide behavior that is consistent with the operating system and has access to all the locales supported by the operating system.
MX validators use the Flex ResourceManager to access locale-specific data from properties files that are included in the Flex SDK. The MX validators provide the same behavior across operating systems, but are limited to the locales provided by the Flex SDK or by the application developer.
The following table lists the Spark and MX validators. When possible, it's best to use the Spark validators in your application:
|
Spark validator |
MX validator |
Description |
|---|---|---|
|
CreditCardValidator |
Validate a credit card number. |
|
|
CurrencyValidator |
CurrencyValidator |
Validate a currency value. |
|
DateValidator |
Validate a date and time value. |
|
|
EmailValidator |
Validate an email address. |
|
|
NumberValidator |
NumberValidator |
Validate a numeric value. |
|
PhoneNumberValidator |
Validate a phone number. |
|
|
SocialSecurityValidator |
Validate a social security number. |
|
|
StringValidator |
Validate a String value. |
|
|
ZipCodeValidator |
Validate a U.S. or Canadian postal code. |
The Spark validators provides the following functionality:
Locale-specific parsing of numbers and currency amounts.
Locale-specific string comparison. For more information, see Sorting and matching.
Locale-specific uppercase and lowercase string conversion.
Support non-European digits in a validation
Validation of negative and positive formats of all numbers and currencies.
Consistency with other applications running on the system.
Operating system updates that include new locales or changes to existing locales are automatically supported.
The Spark validators use of the locale style property to select a locale. The locale style is an inheritable style that you can set for the entire application or specifically for a particular validator. Once set, the locale governs the validation provided by these classes.
If a Spark validator does not explicitly set the locale style, then it uses the value specified by the locale style of the application container. If you do not set the locale style property, the application uses the global default from the defaults.css style sheet, which defaults to en. For more information, see Setting the locale.
You can explicitly configure the validator to use the default locale by setting the locale style to the constant value flash.globalization.LocaleID.DEFAULT.
Validators use the following two properties to specify the item to validate:
Specifies the object containing the property to validate. Set this to an instance of a component or a data model. You use data binding syntax in MXML to specify the value for the source property. This property supports dot-delimited Strings for specifying nested properties.
A String that specifies the name of the property of source that contains the value to validate.
You can set these properties in any of the following ways:
In MXML when you use a validator tag.
In ActionScript by assigning values to the properties.
When you call the validate() method to invoke a validator programmatically. For more information, see Triggering validation programmatically.
You often specify a Flex user-interface control as the value of the source property, and a property of the control to validate as the value of the property property, as the following example shows:
<?xml version="1.0"?>
<!-- validators\ZCValidator.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Declarations>
<mx:ZipCodeValidator id="zipV"
source="{myZip}"
property="text"/>
</fx:Declarations>
<s:TextInput id="phoneInput"/>
<s:TextInput id="myZip"/>
</s:Application>
In this example, you use the Flex ZipCodeValidator to validate the data entered in a TextInput control. The TextInput control stores the input data in its text property.
You trigger validation either automatically in response to an event, or programmatically by an explicit call to the validate() method of a validator.
When you use events, you can cause the validator to execute automatically in response to a user action. For example, you can use the click event of a Button control to trigger validation on the fields of a form, or the valueCommit event of a TextInput control to trigger validation after a user enters information in the control. For more information, see Triggering validation by using events.
You can also trigger a validation programmatically. For example, you might have to inspect multiple, related input fields to perform a single validation. Or you might have to perform conditional validation based on a user input. For example, you may allow a user to select the currency used for payment, such as U.S. dollars or Euros. Therefore, you want to make sure that you invoke a validator configured for the specified currency. In this case, you can make an explicit call to the validate() method to trigger the correct validator for the input value. For more information, see Triggering validation programmatically.
Flex validators can determine when a user enters an incorrect value into a user-interface control. In addition, all validators support the required property, which, if true, specifies that a missing or empty value in a user-interface control causes a validation error. The default value is true. Therefore, a validation error occurs by default if the user fails to enter any required data in a control associated with a validator. To disable this check, set the required property to false. For more information, see Validating required fields.
If a validation error occurs, by default Flex draws a red box around the component associated with the failure. If the user moves the pointer over the component, Flex displays the error message associated with the error.
You can customize the look of the component and the error message associated with the error. For more information on validation errors, see Working with validation errors.
Validation is event driven. You can use events to trigger validation, programmatically create and configure validators in response to events, and listen for events dispatched by validators.
For example, when a validation operation completes, a validator dispatches a valid or invalid event, depending on the results of the validation. You can listen for these events, and then perform any additional processing that your application requires.
Alternatively, Flex components dispatch valid and invalid events, depending on the results of the validation. This lets you listen for the events being dispatched from the component being validated, rather than listening for events dispatched by the validator.
You are not required to listen for validation events. By default, Flex handles a failed validation by drawing a red box around the control that is associated with the source of the data binding. For a successful validation, Flex clears any indicator of a previous failure. For more information, see Working with validation events.
You can trigger validators automatically by associating them with an event. In the following example, the user enters a ZIP code in a TextInput control, and then triggers validation by clicking the Button control:
<?xml version="1.0"?>
<!-- validators\ZCValidatorTriggerEvent.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Declarations>
<mx:ZipCodeValidator id="zipV"
source="{myZip}"
property="text"
trigger="{mySubmit}"
triggerEvent="click"/>
</fx:Declarations>
<s:TextInput id="myZip"/>
<s:Button id="mySubmit" label="Submit"/>
</s:Application>
This example uses the trigger and triggerEvent properties of the ZipCodeValidator class to associate an event with the validator. These properties have the following values:
Specifies the component generating the event that triggers the validator. If omitted, by default Flex uses the value of the source property.
Specifies the event that triggers the validation. If omitted, Flex uses the valueCommit event. Flex dispatches the valueCommit event whenever the value of a control changes. Usually this is when the user removes focus from the component, or when a property value is changed programmatically. If you want a validator to ignore all events, set triggerEvent to an empty string ("").
For information on specific validator classes, see Using standard validators.
You can rewrite the example from the previous section to use default values for the trigger and triggerEvent properties, as the following example shows:
<?xml version="1.0"?>
<!-- validators\ZCValidatorDefEvent.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Declarations>
<mx:ZipCodeValidator id="zipV"
source="{myZip}"
property="text"/>
</fx:Declarations>
<s:TextInput id="myZip"/>
<s:Button id="mySubmit" label="Submit"/>
</s:Application>
By omitting the trigger and triggerEvent properties, Flex triggers the validator when the TextInput control dispatches the valueCommit event. Flex controls dispatch the valueCommit event when its values changes by user interaction or programmatically.
Data binding provides a syntax for automatically copying the value of a property of one object to a property of another object at run time. With data binding, Flex copies the source value to the destination, typically in response to a modification to the source. The source and destination of data bindings are typically Flex components or data models.
In the next example, you bind data entered in a TextInput control to a data model so that the data in the TextInput control is automatically copied to the data model:
<?xml version="1.0"?>
<!-- validators\ValWithDataBinding.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Declarations>
<!-- Define a data model for storing the phone number. -->
<fx:Model id="userInfo">
<phoneInfo>
<phoneNum>{phoneInput.text}</phoneNum>
</phoneInfo>
</fx:Model>
</fx:Declarations>
<!-- Define the TextInput control for entering the phone number. -->
<s:TextInput id="phoneInput"/>
<s:TextInput id="zipCodeInput"/>
</s:Application>
You can use a validator along with a data binding to validate either the source or destination of the data binding, as the following example shows:
<?xml version="1.0"?>
<!-- validators\ValTriggerWithDataBinding.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Declarations>
<!-- Define a data model for storing the phone number. -->
<fx:Model id="userInfo">
<phoneInfo>
<phoneNum>{phoneInput.text}</phoneNum>
</phoneInfo>
</fx:Model>
<!-- Define the PhoneNumberValidator. -->
<mx:PhoneNumberValidator id="pnV"
source="{phoneInput}"
property="text"/>
</fx:Declarations>
<!-- Define the TextInput control for entering the phone number. -->
<s:TextInput id="phoneInput"/>
<s:TextInput id="zipCodeInput"/>
</s:Application>
This example uses a PhoneNumberValidator to validate the data entered in the TextInput control. In this example, the following occurs:
You assign the validator to the source of the data binding.
You use the default event, valueCommit, on the TextInput control to trigger the validator. This means the validator executes when the user removes focus from the TextInput control by selecting the TextInput control for the ZIP code.
Flex updates the destination of the data binding on every change to the source. This means that the userInfo.phoneNum field updates on every change to the TextInput control, while the validator executes only when the user removes focus from the TextInput control to trigger the valueCommit event. You can use the validator's triggerEvent property to specify a different event to trigger the validation.
In a model-view-controller (MVC) design pattern, you isolate the model from the view and controller portions of the application. In the previous example, the data model represents the model, and the TextInput control and validator represents the view.
The TextInput control is not aware that its data is bound to the data model, or that there is any binding on it at all. Since the validator is also assigned to the TextInput control, you have kept the model and view portions of your application separate and can modify one without affecting the other.
However, there is nothing in Flex to prohibit you from assigning a validator to the data model, as the following example shows:
<?xml version="1.0"?>
<!-- validators\ValTriggerWithDataBindingOnModel.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Declarations>
<!-- Define a data model for storing the phone number. -->
<fx:Model id="userInfo">
<phoneInfo>
<phoneNum>{phoneInput.text}</phoneNum>
</phoneInfo>
</fx:Model>
<!-- Define the PhoneNumberValidator. -->
<mx:PhoneNumberValidator id="pnV"
source="{userInfo}"
property="phoneNum"
trigger="{phoneInput}"
listener="{phoneInput}"/>
</fx:Declarations>
<!-- Define the TextInput control for entering the phone number. -->
<s:TextInput id="phoneInput"/>
<s:TextInput id="zipCodeInput"/>
</s:Application>
In this example, you trigger the data validator by using the valueCommit event of the TextInput control, but assign the validator to a field of the data model, rather than to a property of the TextInput control.
This example also uses the listener property of the validator. This property configures the validator to display validation error information on the specified object, rather than on the source of the validation. In this example, the source of the validation is a model, so you display the visual information on the TextInput control that provided the data to the model. For more information, see Specifying a listener for validation.
If the model has a nesting structure of elements, you use dot-delimited Strings with the source property to specify the model element to validate, as the following example shows:
<?xml version="1.0"?>
<!-- validators\ValTriggerWithDataBindingComplexModel.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Declarations>
<!-- Define a data model for storing the phone number. -->
<fx:Model id="userInfo">
<user>
<phoneInfo>
<homePhoneNum>{homePhoneInput.text}</homePhoneNum>
<cellPhoneNum>{cellPhoneInput.text}</cellPhoneNum>
</phoneInfo>
</user>
</fx:Model>
<!-- Define the PhoneNumberValidator. -->
<mx:PhoneNumberValidator id="hPNV"
source="{userInfo.phoneInfo}"
property="homePhoneNum"
trigger="{homePhoneInput}"
listener="{homePhoneInput}"/>
<!-- Define the PhoneNumberValidator. -->
<mx:PhoneNumberValidator id="cPNV"
source="{userInfo.phoneInfo}"
property="cellPhoneNum"
trigger="{cellPhoneInput}"
listener="{cellPhoneInput}"/>
</fx:Declarations>
<!-- Define the TextInput controls for entering the phone number. -->
<s:Label text="Home Phone:"/>
<s:TextInput id="homePhoneInput"/>
<s:Label text="Cell Phone:"/>
<s:TextInput id="cellPhoneInput"/>
</s:Application>
All validators define a validate() method that you can call to invoke a validator directly, rather than triggering the validator automatically by using an event.
The validate() method has the following signature:
validate(value:Object = null, supressEvents:Boolean = false):ValidationResultEvent
The arguments have the following values:
If value is null, use the source and property properties to specify the data to validate. If value is non-null, it specifies a field of an object relative to the this keyword, which means an object in the scope of the document.
You should also set the Validator.listener property when you specify the value argument. When a validation occurs, Flex applies visual changes to the object specified by the listener property. By default, Flex sets the listener property to the value of the source property. However, because you do not specify the source property when you pass the value argument, you should set it explicitly. For more information, see Specifying a listener for validation.
If false, dispatch either the valid or invalid event on completion. If true, do not dispatch events.
This method returns an event object containing the results of the validation that is an instance of the ValidationResultEvent class. For more information on using the return result, see Handling the return value of the validate() method.
In the following example, you create and invoke a validator programmatically in when a user clicks a Button control:
<?xml version="1.0"?>
<!-- validators\ValTriggerProg.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Script>
<![CDATA[
// Import ZipCodeValidator.
import mx.validators.ZipCodeValidator;
private var v:ZipCodeValidator = new ZipCodeValidator();
private function performValidation():void {
v.domain = "US or Canada";
// Set the listener property to the component
// used to display validation errors.
v.listener=myZip;
v.validate(myZip.text);
}
]]>
</fx:Script>
<s:TextInput id="myZip"/>
<s:Button label="Submit" click="performValidation();"/>
</s:Application>
Notice that you are still using an event to trigger the performValidation() function that creates and invokes the validator, but the event itself does not automatically invoke the validator.
Any errors in the validator are shown on the associated component, just as if you had triggered the validation directly by using an event.
You may want to inspect the return value from the validate() method to perform some action when the validation succeeds or fails. The validate() method returns an event object with a type defined by the ValidationResultEvent class.
The ValidationResultEvent class defines several properties, including the type property. The type property of the event object contains either ValidationResultEvent.VALID or ValidationResultEvent.INVALID, based on the validation results. You can use this property as part of your validation logic, as the following example shows:
<?xml version="1.0"?>
<!-- validators\ValTriggerProgProcessReturnResult.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Script>
<![CDATA[
// Import the ValidationResultEvent class.
import mx.events.ValidationResultEvent;
import mx.validators.ZipCodeValidator;
public var v:ZipCodeValidator = new ZipCodeValidator();
// Define variable for storing the validation event object.
public var vResult:ValidationResultEvent;
public function performValidation():void {
v.domain = "US or Canada";
v.listener=myZip;
vResult = v.validate(myZip.text);
if (vResult.type==ValidationResultEvent.VALID) {
// Validation succeeded.
myTA.text='OK';
}
else {
// Validation failed.
myTA.text='Fail';
}
}
]]>
</fx:Script>
<s:TextInput id="myZip"/>
<s:Button label="Submit" click="performValidation();"/>
<s:TextArea id="myTA"/>
</s:Application>
The ValidationResultEvent class has additional properties that you can use when processing validation events. For more information, see Working with validation events.
The DateValidator and CreditCardValidator can validate multiple fields by using a single validator. A CreditCardValidator examines one field that contains the credit card number and a second field that contains the credit card type. The DateValidator can examine a single field that contains a date, or multiple fields that together make up a date.
When you validate an object that contains multiple properties that are set independently, you often cannot use events to automatically trigger the validator because no single field contains all of the information required to perform the validation.
One way to validate a complex object is to call the validate() method of the validator based on some type of user interaction. For example, you might want to validate the multiple fields that make up a date in response to the click event of a Button control, as the following example shows:
<?xml version="1.0"?>
<!-- validators\DateAndCC.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Declarations>
<!-- Define the data model. -->
<fx:Model id="date">
<dateInfo>
<month>{monthInput.text}</month>
<day>{dayInput.text}</day>
<year>{yearInput.text}</year>
</dateInfo>
</fx:Model>
<!-- Define the validators. -->
<mx:DateValidator id="dayV"
triggerEvent=""
daySource="{dayInput}"
dayProperty="text"
monthSource="{monthInput}"
monthProperty="text"
yearSource="{yearInput}"
yearProperty="text"/>
</fx:Declarations>
<!-- Define the form to populate the model. -->
<s:Form>
<s:TextInput id="monthInput"/>
<s:TextInput id="dayInput"/>
<s:TextInput id="yearInput"/>
</s:Form>
<!-- Define the button to trigger validation. -->
<s:Button label="Submit"
click="dayV.validate();"/>
</s:Application>
The validator in this example examines all three input fields. If any field is invalid, validation fails. The validator highlights only the invalid fields that failed. For more information on how validators signal validation errors, see Working with validation errors. For more information on the DateValidator and CreditCardValidator, see Using standard validators.
You can invoke multiple validators programmatically from a single function. In this example, you use the ZipCodeValidator and PhoneNumberValidator validators to validate the ZIP code and phone number input to a data model.
<?xml version="1.0"?>
<!-- validators\ValidatorCustomFuncStaticVals.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Script>
<![CDATA[
// Import event class.
import mx.events.ValidationResultEvent;
// Define variable for storing the validation event object.
private var vResult:ValidationResultEvent;
private function validateZipPhone():void {
// Validate the ZIP code.
vResult = zipV.validate();
// If the ZIP code is invalid,
// do not move on to the next field.
if (vResult.type==ValidationResultEvent.INVALID)
return;
// Validate the phone number.
vResult = pnV.validate();
// If the phone number is invalid,
// do not move on to the validation.
if (vResult.type==ValidationResultEvent.INVALID)
return;
}
]]>
</fx:Script>
<fx:Declarations>
<fx:Model id="person">
<userInfo>
<zipCode>{zipCodeInput.text}</zipCode>
<phoneNumber>{phoneNumberInput.text}</phoneNumber>
</userInfo>
</fx:Model>
<!-- Define the validators. -->
<mx:ZipCodeValidator id="zipV"
source="{zipCodeInput}"
property="text"/>
<mx:PhoneNumberValidator id="pnV"
source ="{phoneNumberInput}"
property="text"/>
</fx:Declarations>
<s:Form>
<s:FormItem>
<s:TextInput id="zipCodeInput"/>
</s:FormItem>
<s:FormItem>
<s:TextInput id="phoneNumberInput"/>
</s:FormItem>
</s:Form>
<s:Button label="Validate"
click="validateZipPhone();"/>
</s:Application>
In this example, you use the predefined ZipCodeValidator and PhoneNumberValidator to validate user information as the user enters it. Then, when the user clicks the Submit button to submit the form, you validate that the ZIP code is actually within the specified area code of the phone number.
You can also use the static validateAll() method to invoke all of the validators in an Array. This method returns an Array containing one ValidationResultEvent object for each validator that failed, and an empty Array if all validators succeed. The following example uses this method to invoke two validators in response to the click event for the Button control:
<?xml version="1.0"?>
<!-- validators\ValidatorMultipleValids.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
creationComplete="initValidatorArray();">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Script>
<![CDATA[
import mx.validators.Validator;
// Define the validator Array.
private var myValidators:Array;
private function initValidatorArray():void {
myValidators=[zipV, pnV];
}
]]>
</fx:Script>
<fx:Declarations>
<fx:Model id="person">
<userInfo>
<zipCode>{zipCodeInput.text}</zipCode>
<phoneNumber>{phoneNumberInput.text}</phoneNumber>
</userInfo>
</fx:Model>
<!-- Define the validators. -->
<mx:ZipCodeValidator id="zipV"
source="{zipCodeInput}"
property="text"/>
<mx:PhoneNumberValidator id="pnV"
source ="{phoneNumberInput}"
property="text"/>
</fx:Declarations>
<s:Form>
<s:FormItem>
<s:TextInput id="zipCodeInput"/>
</s:FormItem>
<s:FormItem>
<s:TextInput id="phoneNumberInput"/>
</s:FormItem>
</s:Form>
<s:Button label="Validate"
click="Validator.validateAll(myValidators);"/>
</s:Application>
You can define a reusable validator so that you can use it to validate multiple fields. To make it reusable, you programmatically set the source and property properties to specify the field to validate, or pass that information to the validate() method, as the following example shows:
<?xml version="1.0"?>
<!-- validators\ReusableVals.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Script>
<![CDATA[
import flash.events.Event;
private function performValidation(eventObj:Event):void {
zipV.listener=eventObj.currentTarget;
zipV.validate(eventObj.currentTarget.text);
}
]]>
</fx:Script>
<fx:Declarations>
<mx:ZipCodeValidator id="zipV"
triggerEvent=""/>
</fx:Declarations>
<s:TextInput id="shippingZip"
focusOut="performValidation(event);"/>
<s:TextInput id="billingZip"
focusOut="performValidation(event);"/>
</s:Application>
In this example, you have two address areas for a customer: one for a billing address and one for a shipping address. Both addresses have a ZIP code field, so you can reuse a single ZipCodeValidator for both fields. The event listener for the focusOut event passes the field to validate to the validate() method.
Alternatively, you can write the performValidation() function as the following example shows:
<?xml version="1.0"?>
<!-- validators\ReusableValsSpecifySource.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Script>
<![CDATA[
import flash.events.Event;
private function performValidation(eventObj:Event):void {
zipV.source = eventObj.currentTarget;
zipV.property = "text";
zipV.validate();
}
]]>
</fx:Script>
<fx:Declarations>
<mx:ZipCodeValidator id="zipV"
triggerEvent=""/>
</fx:Declarations>
<s:TextInput id="shippingZip"
focusOut="performValidation(event);"/>
<s:TextInput id="billingZip"
focusOut="performValidation(event);"/>
</s:Application>
By invoking a validator programmatically, you can use conditional logic in your application to determine which of several validators to invoke, set validator properties, or perform other preprocessing or postprocessing as part of the validation.
In the next example, you use a Button control to invoke a validator, but the application first determines which validator to execute, based on user input:
<?xml version="1.0"?>
<!-- validators\ConditionalVal.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Script>
<![CDATA[
import mx.events.ValidationResultEvent;
private var vEvent:ValidationResultEvent;
private function validateData():void {
if (String(country.selectedValue) == "Canada") {
vEvent = zipCN.validate(zipInput.text);
}
else {
vEvent = zipUS.validate(zipInput.text);
}
}
]]>
</fx:Script>
<fx:Declarations>
<mx:ZipCodeValidator id="zipUS"
domain="US Only"
listener="{zipInput}"/>
<mx:ZipCodeValidator id="zipCN"
domain="Canada Only"
listener="{zipInput}"/>
<s:RadioButtonGroup id="country"/>
</fx:Declarations>
<s:RadioButton group="{country}" label="US"/>
<s:RadioButton group="{country}" label="Canada"/>
<s:TextInput id="zipInput"/>
<s:Button label="Submit" click="validateData();"/>
</s:Application>
In this example, you use a ZipCodeValidator to validate a ZIP code entered into a TextInput control. However, the validateData() function must first determine whether the ZIP code is for the U.S. or for Canada before performing the validation. In this example, the application uses the RadioButton controls to let the user specify the country as part of entering the ZIP code.
All Flex validators contain a required property that, when set to true, causes validation to fail when a field is empty. You use this property to configure the validator to fail when a user does not enter data in a required input field.
You typically call the validate() method to invoke a validator on a required field. This is often necessary because you cannot guarantee that an event occurs to trigger the validation—an empty input field often means that the user never gave the input control focus.
The following example performs a validation on a required input field:
<?xml version="1.0"?>
<!-- validators\RequiredVal.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Declarations>
<mx:StringValidator id="reqV"
source="{inputA}"
property="text"
required="true"/>
</fx:Declarations>
<s:TextInput id="inputA"/>
<s:Button label="Submit"
click="reqV.validate();"/>
</s:Application>
In this example, the StringValidator executes when the following occurs:
The TextInput control dispatches the valueCommit event. However, to dispatch that event, the user must give the TextInput control focus, and then remove focus. If the user never gives the TextInput control focus, the validator does not trigger, and Flex does not recognize that the control is empty. Therefore, you must call the validate() method to ensure that the validator checks for missing data.
The user clicks the Button control. The validator issues a validation error when the user does not enter any data into the TextInput control. It also issues a validation error if the user enters an invalid String value.
The enabled property of a validator lets you enable and disable a validator. When the value of the enabled property is true, the validator is enabled; when the value is false, the validator is disabled. When a validator is disabled, it dispatches no events, and the validate() method returns null.
For example, you can set the enabled property by using data binding, as the following code shows:
<?xml version="1.0"?>
<!-- validators\EnableVal.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Declarations>
<mx:ZipCodeValidator id="zcVal"
source="{inputA}"
property="text"
required="true"
enabled="{enableV.selected}"/>
</fx:Declarations>
<s:TextInput id="inputA"/>
<s:TextInput/>
<s:CheckBox id="enableV"
label="Validate input?"/>
</s:Application>
In this example, you enable the validator only when the user selects the CheckBox control.
You configure validators to match your application requirements. For example, the StringValidator lets you specify a minimum and maximum length of a valid string. For a String to be considered valid, it must be at least the minimum number of characters long, and less than or equal to the maximum number of characters.
Often, you set validator properties statically, which means that they do not change as your application executes. For example, the following StringValidator defines that the input string must be at least one character long and no longer than 10 characters:
<mx:StringValidator required="true" minlength="1" maxLength="10"/>
User input might also define the properties of the validator. In the following example, you let the user set the minimum and maximum values of a NumberValidator:
<?xml version="1.0"?>
<!-- validators\ConfigWithBinding.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Declarations>
<mx:NumberValidator
source="{inputA}"
property="text"
minValue="{Number(inputMin.text)}"
maxValue="{Number(inputMax.text)}"/>
</fx:Declarations>
<s:TextInput id="inputA"/>
<s:TextInput id="inputMin" text="1"/>
<s:TextInput id="inputMax" text="10"/>
</s:Application>
In this example, you use data binding to configure the properties of the validators.
You should be aware of some guidelines when performing validation on forms. Typically, you associate forms with data models. That lets you trigger validation as part of binding an input user interface control to a field of the data model. You can also perform some of the following actions:
If possible, assign validators to all the individual user-interface controls of the form. You can use a validator even if all that you want to do is to ensure that the user entered a value.
Assign validators to multiple fields when necessary. For example, use the CreditCardValidator or the DateValidator with multiple fields.
If you have any required fields, ensure that you explicitly call the validate() method on the validator. For more information, see Validating required fields.
Define a Submit button to invoke any validators before submitting data to a server. Typically, you use the click event of the Button control to invoke validators programmatically, and then submit the data if all validation succeeds.
The following example uses many of these guidelines to validate a form made up of several TextInput controls:
<?xml version="1.0"?>
<!-- validators\FullApp.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Script>
<![CDATA[
import mx.events.ValidationResultEvent;
private var vResult:ValidationResultEvent;
// Function to validate data and submit it to the server.
private function validateAndSubmit():void {
// Validate the required fields.
vResult = fNameV.validate();
if (vResult.type==ValidationResultEvent.INVALID)
return;
vResult = lNameV.validate();
if (vResult.type==ValidationResultEvent.INVALID)
return;
// Since the date requires 3 fields, perform the validation
// when the Submit button is clicked.
vResult = dayV.validate();
if (vResult.type==ValidationResultEvent.INVALID)
return;
// Invoke any other validators or validation logic to make
// an additional check before submitting the data.
// Submit data to server.
}
]]>
</fx:Script>
<fx:Declarations>
<!-- Define the data model. -->
<fx:Model id="formInfo">
<formData>
<date>
<month>{monthInput.text}</month>
<day>{dayInput.text}</day>
<year>{yearInput.text}</year>
</date>
<name>
<firstName>{fNameInput.text}</firstName>
<lastName>{lNameInput.text}</lastName>
</name>
<phoneNum>{phoneInput.text}</phoneNum>
</formData>
</fx:Model>
<!-- Define the validators. -->
<mx:StringValidator id="fNameV"
required="true"
source="{fNameInput}"
property="text"/>
<mx:StringValidator id="lNameV"
required="true"
source="{lNameInput}"
property="text"/>
<mx:PhoneNumberValidator id="pnV"
source="{phoneInput}"
property="text"/>
<!-- Invoke the DataValidator programmatically. -->
<mx:DateValidator id="dayV"
triggerEvent=""
daySource="{dayInput}" dayProperty="text"
monthSource="{monthInput}" monthProperty="text"
yearSource="{yearInput}" yearProperty="text"/>
</fx:Declarations>
<!-- Define the form to populate the model. -->
<s:Form>
<s:FormItem label="Month">
<s:TextInput id="monthInput"/>
</s:FormItem>
<s:FormItem label="Day">
<s:TextInput id="dayInput"/>
</s:FormItem>
<s:FormItem label="Year">
<s:TextInput id="yearInput"/>
</s:FormItem>
<s:FormItem label="First name">
<s:TextInput id="fNameInput"/>
</s:FormItem>
<s:FormItem label="Last name">
<s:TextInput id="lNameInput"/>
</s:FormItem>
<s:FormItem label="Phone">
<s:TextInput id="phoneInput"/>
</s:FormItem>
</s:Form>
<!-- Define the button to trigger validation. -->
<s:Button label="Submit"
click="validateAndSubmit();"/>
</s:Application>
In this example the following actions occur:
The associated validator executes whenever the TextInput control dispatches a valueCommit event.
The click event for the Button control invokes the validateAndSubmit() function to perform final validation before submitting data to the server.
The validateAndSubmit() function invokes the validators for all required fields.
The validateAndSubmit() function invokes the DateValidator because it requires three different input fields.
Upon detecting the first validation error, the validateAndSubmit() function returns but does not submit the data.
When all validations succeed, the validateAndSubmit() function submits the data to the server.
Subclasses of the UIComponent base class, which include the Flex user-interface components, generally handle validation failures by changing their border color and displaying an error message. When validation succeeds, components hide any existing validation error message and remove any border.
You can configure the content of the error messages and the display characteristics of validation errors.
All Flex validators define default error messages. In most cases, you can override these messages with your own.
The default error messages for all validators are defined by using resource bundles so that you can easily change them as part of localizing your application. You can override the default value of an error message for all validator objects created from a validator class by editing the resource bundles associated with that class.
You edit the error message for a specific validator object by writing a String value to a property of the validator. For example, the PhoneNumberValidator defines a default error message to indicate that an input phone number has the wrong number of digits. You can override the default error message for a specific PhoneNumberValidator object by assigning a new message string to the wrongLengthError property, as the following example shows:
<?xml version="1.0"?>
<!-- validators\PNValidatorErrMessage.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Declarations>
<!-- Define the PhoneNumberValidator. -->
<mx:PhoneNumberValidator id="pnV"
source="{phoneInput}" property="text"
wrongLengthError="Please enter a 10-digit number."/>
</fx:Declarations>
<!-- Define the TextInput control for entering the phone number. -->
<s:TextInput id="phoneInput"/>
<s:TextInput id="zipCodeInput"/>
</s:Application>
By default, the validation error message that appears when you move the mouse pointer over a user-interface control has a red background. You can use the errorTip style to change the color, as the following example shows:
<?xml version="1.0"?>
<!-- validators\PNValidatorErrMessageStyle.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<!-- Use blue for the error message. -->
<fx:Style>
.errorTip { borderColor: #0000FF}
</fx:Style>
<fx:Declarations>
<!-- Define the PhoneNumberValidator. -->
<mx:PhoneNumberValidator id="pnV"
source="{phoneInput}" property="text"
wrongLengthError="Please enter a 10-digit number."/>
</fx:Declarations>
<!-- Define the TextInput control for entering the phone number. -->
<s:TextInput id="phoneInput"/>
<s:TextInput id="zipCodeInput"/>
</s:Application>
In this example, the error message appears in blue.
For Spark components, when a validation error occurs, Flex uses the spark.skins.default.ErrorSkin skin class to draw a red box around the component associated with the failure. You can define a custom skin class to control the display of the validation error. If you define a custom skin class, set the errorSkin style of the Spark component that you are validating to the skin class.
The UIComponent class defines the errorString property that you can use to show a validation error for a component, without actually using a validator class. When you write a String value to the UIComponent.errorString property, Flex draws a red border around the component to indicate the validation error, and the String appears in a ToolTip as the validation error message when you move the mouse over the component, just as if a validator detected a validation error.
To clear the validation error, write an empty String, " ", to the UIComponent.errorString property.
For information on writing custom ToolTip controls, see ToolTip controls.
The errorString property is useful when you want to reset a field that is a source for validation, and prevent a validation error from occurring when you reset the field.
For example, you might provide a form to gather user input. Within your form, you might also provide a button, or other mechanism, that lets the user reset the form. However, clearing form fields that are tied to validators could trigger a validation error. The following example uses the errorString property as part of resetting the text property of a TextInput control to prevent validation errors when the form resets:
<?xml version="1.0"?>
<!-- validators\ResetVal.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Script>
<![CDATA[
import mx.events.ValidationResultEvent;
private var vResult:ValidationResultEvent;
// Function to validate data and submit it to the server.
private function validateAndSubmit():void {
// Validate the required fields.
vResult = zipV.validate();
if (vResult.type==ValidationResultEvent.INVALID)
return;
// Submit data to server.
}
// Clear the input controls and the errorString property
// when resetting the form.
private function resetForm():void {
zipInput.text = '';
zipInput.errorString = '';
}
]]>
</fx:Script>
<fx:Declarations>
<mx:ZipCodeValidator id="zipV"
source="{zipInput}"
property="text"/>
</fx:Declarations>
<s:Form>
<s:FormItem label="Enter ZIP code">
<s:TextInput id="zipInput"/>
</s:FormItem>
<s:FormItem label="Enter Country">
<s:TextInput id="cntryInput"/>
</s:FormItem>
</s:Form>
<!-- Trigger submit. -->
<s:Button label="Submit" click="validateAndSubmit();"/>
<!-- Trigger reset. -->
<s:Button label="Reset" click="resetForm();"/>
</s:Application>
In this example, the function that clears the form items also clears the errorString property associated with each item, clearing any validation errors.
All validators support a listener property. When a validation occurs, Flex applies visual changes to the object specified by the listener property.
By default, Flex sets the listener property to the value of the source property. That means that all visual changes that occur to reflect a validation event occur on the component being validated. However, you might want to validate one component but have validation results apply to a different component, as the following example shows:
<?xml version="1.0"?>
<!-- validators\SetListener.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Declarations>
<mx:ZipCodeValidator id="zipV"
source="{zipCodeInput}"
property="text"
listener="{errorMsg}"/>
</fx:Declarations>
<s:TextInput id="zipCodeInput"/>
<s:TextArea id="errorMsg"/>
</s:Application>
Flex gives you two ways to listen for validation events:
Listen for validation events dispatched by the component being validated.
Flex components dispatch valid and invalid events, depending on the results of the validation. This lets you listen for the events being dispatched from the component being validated, and perform any additional processing on the component based on its validation result.
The event object passed to the event listener is of type Event. For more information, including an example, see Explicitly handling component validation events.
Listen for validation events dispatched by validators.
All validators dispatch valid or invalid events, depending on the results of the validation. You can listen for these events, and then perform any additional processing as required by your validator.
The event object passed to the event listener is of type ValidationResultEvent. For more information, including an example, see Explicitly handing validator validation events.
You are not required to listen for validation events. When these events occur, by default, Flex changes the appropriate border color of the target component, displays an error message for an invalid event, or hides any previous error message for a valid event.
Sometimes you might want to perform some additional processing for a component if a validation fails or succeeds. In that case, you can handle the valid and invalid events yourself. The following example defines an event listener for the invalid event to perform additional processing when a validation fails:
<?xml version="1.0"?>
<!-- validators\ValCustomEventListener -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Script>
<![CDATA[
// Import event class.
import flash.events.Event;
// Define vars for storing text colors.
private var errorTextColor:Object = "red";
private var currentTextColor:Object;
// Initialization event handler for getting default text color.
private function myCreationComplete(eventObj:Event):void {
currentTextColor = getStyle('color');
}
// For an invalid event, change the text color.
private function handleInvalidVal(eventObject:Event):void {
setStyle('color', errorTextColor);
}
// For a valid event, restore the text color.
private function handleValidVal(eventObject:Event):void {
setStyle('color', currentTextColor);
}
]]>
</fx:Script>
<fx:Declarations>
<mx:PhoneNumberValidator source="{phoneInput}" property="text"/>
</fx:Declarations>
<s:TextInput id="phoneInput"
initialize="myCreationComplete(event);"
invalid="handleInvalidVal(event);"
valid="handleValidVal(event);"/>
<s:TextInput id="zipInput"/>
</s:Application>
To explicitly handle the valid and invalid events dispatched by validators, define an event listener, as the following example shows:
<?xml version="1.0"?>
<!-- validators\ValEventListener.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Script>
<![CDATA[
// Import event class
import mx.events.ValidationResultEvent;
private function handleValid(event:ValidationResultEvent):void {
if(event.type==ValidationResultEvent.VALID)
submitButton.enabled = true;
else
submitButton.enabled = false;
}
// Submit form is everything is valid.
private function submitForm():void {
// Handle submit.
}
]]>
</fx:Script>
<fx:Declarations>
<mx:ZipCodeValidator
source="{inputZip}" property="text"
valid="handleValid(event);"
invalid="handleValid(event);"/>
</fx:Declarations>
<s:TextInput id="inputZip"/>
<s:TextInput id="inputPn"/>
<s:Button id="submitButton"
label="Submit"
enabled="false"
click="submitForm();"/>
</s:Application>
In this example, the Button control is disabled until the TextInput field contains a valid ZIP code. The type property of the event object is either ValidationResultEvent.VALID or ValidationResultEvent.INVALID, based on the result of the validation.
Within the event listener, you can use all the properties of the ValidationResultEvent class, including the following:
A String that contains the name of the field that failed validation and triggered the event.
A String that contains all the validator error messages created by the validation.
An Array of ValidationResult objects, one for each field examined by the validator. For a successful validation, the ValidationResultEvent.results Array property is empty. For a validation failure, the ValidationResultEvent.results Array property contains one ValidationResult object for each field checked by the validator, both for fields that failed the validation and for fields that passed. Examine the ValidationResult.isError property to determine if the field passed or failed the validation.
Flex includes the Validator subclasses. You use these validators for common types of data, including credit card numbers, dates, e-mail addresses, numbers, phone numbers, Social Security numbers, strings, and ZIP codes.
The CreditCardValidator class validates that a credit card number is the correct length, has the correct prefix, and passes the Luhn mod10 algorithm for the specified card type. This validator does not check whether the credit card is an actual active credit card account.
You typically use the cardNumberSource and cardNumberProperty properties to specify the location of the credit card number, and the cardTypeSource and cardTypeProperty properties to specify the location of the credit card type to validate.
The CreditCardValidator class validates that a credit card number is the correct length for the specified card type, as follows:
Visa: 13 or 16 digits
MasterCard: 16 digits
Discover: 16 digits
American Express: 15 digits
DinersClub: 14 digits, or 16 digits if it also functions as a MasterCard
You specify the type of credit card number to validate by assigning a constant to the cardTypeProperty property. In MXML, valid constant values are:
"American Express"
"Diners Club"
"Discover"
"MasterCard"
"Visa"
In ActionScript, you can use the following constants to set the cardTypeProperty property:
CreditCardValidatorCardType.AMERICAN_EXPRESS
CreditCardValidatorCardType.DINERS_CLUB
CreditCardValidatorCardType.DISCOVER
CreditCardValidatorCardType.MASTER_CARD
CreditCardValidatorCardType.VISA
The following example validates a credit card number based on the card type that the users specifies. Any validation errors propagate to the Application object and open an Alert window.
<?xml version="1.0"?>
<!-- validators\CCExample.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<fx:Declarations>
<mx:CreditCardValidator id="ccV"
cardTypeSource="{cardTypeCombo.selectedItem}"
cardTypeProperty="data"
cardNumberSource="{cardNumberInput}"
cardNumberProperty="text"/>
</fx:Declarations>
<s:Form id="creditCardForm">
<s:FormItem label="Card Type">
<s:ComboBox id="cardTypeCombo">
<s:dataProvider>
<s:ArrayList>
<fx:Object label="American Express"
data="American Express"/>
<fx:Object label="Diners Club"
data="Diners Club"/>
<fx:Object label="Discover"
data="Discover"/>
<fx:Object label="MasterCard"
data="MasterCard"/>
<fx:Object label="Visa"
data="Visa"/>
</s:ArrayList>
</s:dataProvider>
</s:ComboBox>
</s:FormItem>
<s:FormItem label="Credit Card Number">
<s:TextInput id="cardNumberInput"/>
</s:FormItem>
<s:FormItem>
<s:Button label="Check Credit" click="ccV.validate();"/>
</s:FormItem>
</s:Form>
</s:Application>
The following example performs a similar validation, but uses the source and property properties to specify an object that contains the credit card information. In this example, you use the listener property to configure the validator to display validation error information on the TextInput control:
<?xml version="1.0"?>
<!-- validators\CCExampleSource.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Script>
<![CDATA[
[Bindable]
public var ccObj:Object = {cardType:String, cardNumber:String};
public function valCC():void
{
// Populate ccObj with the data from the form.
ccObj.cardType = cardTypeCombo.selectedItem.data;
ccObj.cardNumber = cardNumberInput.text;
// Validate ccObj.
ccV.validate();
}
]]>
</fx:Script>
<fx:Declarations>
<mx:CreditCardValidator id="ccV"
source="{this}"
property="ccObj"
listener="{cardNumberInput}"/>
</fx:Declarations>
<s:Form id="creditCardForm">
<s:FormItem label="Card Type">
<s:ComboBox id="cardTypeCombo">
<s:dataProvider>
<s:ArrayList>
<fx:Object label="American Express"
data="American Express"/>
<fx:Object label="Diners Club"
data="Diners Club"/>
<fx:Object label="Discover"
data="Discover"/>
<fx:Object label="MasterCard"
data="MasterCard"/>
<fx:Object label="Visa"
data="Visa"/>
</s:ArrayList>
</s:dataProvider>
</s:ComboBox>
</s:FormItem>
<s:FormItem label="Credit Card Number">
<s:TextInput id="cardNumberInput"/>
</s:FormItem>
<s:FormItem>
<s:Button label="Check Credit" click="valCC();"/>
</s:FormItem>
</s:Form>
</s:Application>
The Spark CurrencyValidator class checks that a string is a valid currency expression based on a set of parameters and the current locale. The CurrencyValidator class defines the properties that let you specify the format of the currency value, whether to allow negative values, and the precision of the values, and other options.
The digits of the input String can use national digits defined in the flash.globalization.NationalDigitsType class.
The following example uses the CurrencyValidator class to validate a currency value entered in U.S. dollars and in Euros:
<?xml version="1.0"?>
<!-- validators\SparkCurrencyExample.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<s:layout>
<s:VerticalLayout paddingTop="10" paddingLeft="10"/>
</s:layout>
<fx:Declarations>
<!-- Example for US currency. -->
<s:CurrencyValidator id="usV"
locale="en-US"
source="{priceUS}" property="text"
trigger="{valButton}"
triggerEvent="click"/>
<!-- Example for European currency. -->
<s:CurrencyValidator id="eurV"
locale="fr-FR"
source="{priceEU}" property="text"
trigger="{valButton}"
triggerEvent="click"/>
</fx:Declarations>
<s:Label text="Enter a US-formatted price:"/>
<s:TextInput id="priceUS"/>
<s:Label text="Enter a European-formatted price:"/>
<s:TextInput id="priceEU"/>
<s:Button id="valButton" label="Validate Currencies"/>
</s:Application>
In this example, you explicitly specify the locale for the two validators, rather than relying on the default. Use the first validator to validate currency values for a U.S. locale. Acceptable values include: $23.00, USD 23.00, or 123,456.00. Invalid values include: 2,37 EUR and €2.37.
The second validator specifies the locale as fr-FR for French currencies. Valid values include: 2,37, 2,37 EUR, and €2.37. Invalid values include: $23.00 and USD 23.00.
The DateValidator class validates that a String, Date, or Object contains a proper date and matches a specified format. Users can enter a single digit or two digits for month, day, and year. By default, the validator ensures that the following information is provided:
The month is between 1 and 12 (or 0-11 for Date objects)
The day is between 1 and 31
The year is a number
If you specify a single String to validate, the String can contain digits and the formatting characters that the allowedFormatChars property specifies, including the slash (/), backslash (\), dash (-), and period (.) characters. By default, the input format of the date in a String is "mm/dd/yyyy" where "mm" is the month, "dd" is the day, and "yyyy" is the year. You can use the inputFormat property to specify a different format.
You can also specify to validate a date represented by a single Object, or by multiple fields of different objects. For example, you could use a data model that contains three fields that represent the day, month, and year portions of a date, or three TextInput controls that let a user enter a date as three separate fields. Even if you specify a date format that excludes a day, month, or year element, you must specify all three fields to the validator.
The following table describes how to specify the date to the DateValidator:
|
Validation source |
Required properties |
Default listener |
|---|---|---|
|
String object containing the date |
Use the source and property properties to specify the String. |
Flex associates error messages with the field specified by the property property. |
|
Date object containing the date |
Use the source and property properties to specify the Date. |
Flex associates error messages with the field specified by the property property. |
|
Object or multiple fields containing the day, month, and year |
Use all of the following properties to specify the day, month, and year inputs: daySource, dayProperty, monthSource, monthProperty, yearSource, and yearProperty. |
Flex associates error messages with the field specified by the daySource, monthSource, and yearSource properties, depending on the field that caused the validation error. |
The following example validates a date entered into a form:
<?xml version="1.0"?>
<!-- validators\DateExample.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Declarations>
<mx:DateValidator id="dateV"
daySource="{dayInput}" dayProperty="text"
monthSource="{monthInput}" monthProperty="text"
yearSource="{yearInput}" yearProperty="text"/>
<!-- Alternate method for a single field containing the date. -->
<fx:Model id="alternateDate">
<dateInfo>
<date>{dateInput.text}</date>
</dateInfo>
</fx:Model>
<mx:DateValidator id="stringDateV"
source="{dateInput}" property="text"
inputFormat="dd/mm/yyyy"
allowedFormatChars="*#~/"/>
</fx:Declarations>
<s:Form >
<s:FormItem label="Month">
<s:TextInput id="monthInput"/>
</s:FormItem>
<s:FormItem label="Day">
<s:TextInput id="dayInput"/>
</s:FormItem>
<s:FormItem label="Year">
<s:TextInput id="yearInput"/>
</s:FormItem>
<s:FormItem>
<s:Button label="Check Date" click="dateV.validate();"/>
</s:FormItem>
</s:Form>
<s:Form>
<s:FormItem label="Date of Birth (dd/mm/yyyy)">
<s:TextInput id="dateInput"/>
</s:FormItem>
<s:FormItem>
<s:Button label="Check Date" click="stringDateV.validate();"/>
</s:FormItem>
</s:Form>
</s:Application>
In the next example, you validate a Date object:
<?xml version="1.0"?>
<!-- validators\DateObjectExample.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<fx:Script>
<![CDATA[
import mx.controls.Alert;
// myDate is set to the current date and time.
[Bindable]
public var myDate:Date = new Date();
]]>
</fx:Script>
<fx:Declarations>
<mx:DateValidator id="dateV"
source="{this}" property="myDate"
valid="Alert.show('Validation Succeeded!');"/>
</fx:Declarations>
<s:Button label="Check Date" click="dateV.validate();"/>
</s:Application>
The EmailValidator class validates that a string has an at sign character (@) and a period character (.) in the domain. You can use IP domain names if they are enclosed in square brackets; for example, myname@[206.132.22.1]. You can use individual IP numbers from 0 to 255. This validator does not check whether the domain and user name actually exist.
The following example validates an e-mail address to ensure that it is formatted correctly:
<?xml version="1.0"?>
<!-- validators\EmailExample.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<s:Form id="contactForm">
<s:FormItem id="homePhoneItem" label="Home Phone">
<s:TextInput id="homePhoneInput"/>
</s:FormItem>
<s:FormItem id="cellPhoneItem" label="Cell Phone">
<s:TextInput id="cellPhoneInput"/>
</s:FormItem>
<s:FormItem id="emailItem" label="Email">
<s:TextInput id="emailInput"/>
</s:FormItem>
</s:Form>
<fx:Declarations>
<mx:PhoneNumberValidator id="pnVHome"
source="{homePhoneInput}" property="text"/>
<mx:PhoneNumberValidator id="pnVCell"
source="{cellPhoneInput}" property="text"/>
<mx:EmailValidator id="emV"
source="{emailInput}" property="text"/>
</fx:Declarations>
</s:Application>
The Spark NumberValidator class ensures that a string represents a valid number for the current locale. This validator can ensure that the input falls within a given range, is an integer, is non-negative, does not exceed a specified precision, and other options. The NumberValidator also correctly validates formatted numbers (for example, "12,345.67").
The digits of the input String can use national digits defined in the flash.globalization.NationalDigitsType class.
The following example uses the NumberValidator class to ensure that an integer is between 1 and 10:
<?xml version="1.0"?>
<!-- validators\SparkNumberExample.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
width="700">
<s:Form >
<s:FormItem
label="Number of Widgets (max 10 per customer)">
<s:TextInput id="quantityInput"/>
</s:FormItem>
<s:FormItem >
<s:Button label="Submit"/>
</s:FormItem>
</s:Form>
<fx:Declarations>
<s:NumberValidator id="numV"
source="{quantityInput}" property="text"
minValue="1" maxValue="10" domain="int"/>
</fx:Declarations>
</s:Application>
The PhoneNumberValidator class validates that a string is a valid phone number. A valid phone number contains at least 10 digits, plus additional formatting characters. This validator does not check if the phone number is an actual active phone number.
The following example uses two PhoneNumberValidator tags to ensure that the home and mobile phone numbers are entered correctly:
<?xml version="1.0"?>
<!-- validators\PhoneExample.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<s:Form id="contactForm">
<s:FormItem id="homePhoneItem" label="Home Phone">
<s:TextInput id="homePhoneInput"/>
</s:FormItem>
<s:FormItem id="cellPhoneItem" label="Cell Phone">
<s:TextInput id="cellPhoneInput"/>
</s:FormItem>
<s:FormItem id="emailItem" label="Email">
<s:TextInput id="emailInput"/>
</s:FormItem>
</s:Form>
<fx:Declarations>
<mx:PhoneNumberValidator id="pnVHome"
source="{homePhoneInput}" property="text"/>
<mx:PhoneNumberValidator id="pnVCell"
source="{cellPhoneInput}" property="text"/>
<mx:EmailValidator id="emV"
source="{emailInput}" property="text"/>
</fx:Declarations>
</s:Application>
The RegExpValidator class lets you use a regular expression to validate a field. You pass a regular expression to the validator by using the expression property, and additional flags to control the regular expression pattern matching by using the flags property.
The validation is successful if the validator can find a match of the regular expression in the field to validate. A validation error occurs when the validator finds no match.
You use regular expressions with the RegExpValidator. For information on writing regular expressions, see ActionScript 3.0 Developer's Guide.
The RegExpValidator class dispatches the valid and invalid events. For an invalid event, the event object is an instance of the ValidationResultEvent class, and it contains an Array of ValidationResult objects.
However, for a valid event, the ValidationResultEvent object contains an Array of RegExpValidationResult objects. The RegExpValidationResult class is a child class of the ValidationResult class, and contains additional properties that you use with regular expressions, including the following:
An integer that contains the starting index in the input String of the match.
A String that contains the substring of the input String that matches the regular expression.
An Array of Strings that contains parenthesized substring matches, if any. If no substring matches are found, this Array is of length 0. Use matchedSubStrings[0] to access the first substring match.
The following example uses the regular expression ABC\d to cause the validator to match a pattern consisting of the letters A, B, and C in sequence followed by any digit:
<?xml version="1.0"?>
<!-- validators\RegExpExample.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<fx:Script>
<![CDATA[
import mx.events.ValidationResultEvent;
import mx.validators.*;
private function handleResult(event:ValidationResultEvent):void {
if (event.type == "valid")
{
// For valid events, the results Array contains
// RegExpValidationResult objects.
var xResult:RegExpValidationResult;
myTA.text="";
for (var i:uint = 0; i < event.results.length; i++)
{
xResult = event.results[i];
myTA.text=myTA.text + xResult.matchedIndex + " " +
xResult.matchedString + "\n";
}
}
else
{
// Not necessary, but if you needed to access it,
// the results array contains ValidationResult objects.
var result:ValidationResult;
myTA.text="";
}
}
]]>
</fx:Script>
<fx:Declarations>
<mx:RegExpValidator id="regExpV"
source="{exp}" property="text"
flags="g"
expression="{source.text}"
valid="handleResult(event);"
invalid="handleResult(event);"/>
</fx:Declarations>
<s:Form>
<s:FormItem label="Search string">
<s:TextInput id="exp"/>
</s:FormItem>
<s:FormItem label="Regular expression">
<s:TextInput id="source" text="ABC\d"/>
</s:FormItem>
<s:FormItem label="Results">
<s:TextArea id="myTA"/>
</s:FormItem>
</s:Form>
</s:Application>
In this example, you specify the regular expression in the TextInput control named source, and bind it to the expression property of the validator. You can modify the regular expression by entering a new expression in the TextInput control. A value of g for the flags property specifies to find multiple matches in the input field.
The event handler for the valid event writes to the TextArea control the index in the input String and matching substring of all matches of the regular expression. The invalid event handler clears the TextArea control.
The SocialSecurityValidator class validates that a string is a valid United States Social Security Number. This validator does not check if the number is an existing Social Security Number.
The following example validates a Social Security Number:
<?xml version="1.0"?>
<!-- validators\SSExample.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<s:Form id="identityForm">
<s:FormItem id="ssnItem" label="Social Security Number">
<s:TextInput id="ssnField"/>
</s:FormItem>
<s:FormItem id="licenseItem" label="Driver's License Number">
<s:TextInput id="licenseInput"/> <!-- Not validated -->
</s:FormItem>
</s:Form>
<fx:Declarations>
<mx:SocialSecurityValidator id="ssV"
source="{ssnField}" property="text"/>
</fx:Declarations>
</s:Application>
The StringValidator class validates that a string length is within a specified range. The following example ensures that a string is between 6 and 12 characters long:
<?xml version="1.0"?>
<!-- validators\StringExample.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<s:Form id="membershipForm">
<s:FormItem id="fullNameItem" label="Full Name">
<!-- Not validated -->
<s:TextInput id="fullNameInput"/>
</s:FormItem>
<s:FormItem id="userNameItem" label="Username">
<s:TextInput id="userNameInput"/>
</s:FormItem>
</s:Form>
<fx:Declarations>
<mx:StringValidator source="{userNameInput}" property="text"
minLength="6" maxLength="12"/>
</fx:Declarations>
</s:Application>
The ZipCodeValidator class validates that a string has the correct length for a five-digit ZIP code, a five-digit+four-digit United States ZIP code, or a Canadian postal code.
The following example validates either a United States ZIP code or a Canadian postal code:
<?xml version="1.0"?>
<!-- validators\ZCExample.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<s:Form id="addressForm">
<s:FormItem id="zipCodeItem" label="Zip Code">
<s:TextInput id="zipInput"/>
</s:FormItem>
<s:FormItem id="submitArea">
<s:Button label="Submit"/>
</s:FormItem>
</s:Form>
<fx:Declarations>
<mx:ZipCodeValidator id="zipV"
source="{zipInput}" property="text"
domain="US or Canada"/>
</fx:Declarations>
</s:Application>
Navigation
Adobe and Adobe Flash Platform are either registered trademarks or trademarks of Adobe Systems Incorporated in the United States and/or other countries and are used by permission from Adobe. No other license to the Adobe trademarks are granted.