Data validators let you validate the data in an object. Flex supplies a number of standard validators that you can use in your application, but you can also define custom validators for your specific application needs.
For information on the standard validators, see Validating Data.
The data that a user enters in a user interface might or might not be appropriate for 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 in a TextInput control.
Flex includes a set of validators for common types of user input data, such as ZIP codes, phone numbers, and credit cards. Although Flex supplies a number of commonly used validators, your application may require you to create custom validator classes. The mx.validators.Validator class is an ActionScript class that you can extend to add your own validation logic. Your classes can extend the functionality of an existing validator class, or you can implement new functionality in your custom validator class.
The following image shows the class hierarchy for validators:
Your custom validator class must contain an override of the protected Validator.doValidation() method that takes a single argument, value, of type Object, and returns an Array of ValidationResult objects. You return one ValidationResult object for each field that the validator examines and that fails the validation. For fields that pass the validation, you omit the ValidationResult object.
You do not have to create a ValidationResult object for fields that validate successfully. Flex creates those ValidationResult objects for you.
The base Validator class implements the logic to handle required fields by using the required property. When set to true, this property specifies that a missing or empty value in a user-interface control causes a validation error. To disable this verification, set this property to false.
In the doValidation() method of your validator class, you typically call the base class's doValidation() method to perform the verification for a required field. If the user did not enter a value, the base class issues a validation error stating that the field is required.
The remainder of the doValidation() method contains your custom validation logic.
The doValidation() method returns an Array of ValidationResult objects, one for each field that generates a validation error. The ValidationResult class defines several properties that let you record information about any validation failures, including the following:
A String that contains an error code. You can define your own error codes for your custom validators.
A String that contains the error message. You can define your own error messages for your custom validators.
A Boolean value that indicates whether or not the result is an error. Set this property to true.
A String that specifies the name of the subfield associated with the ValidationResult object.
In your override of the doValidation() method, you can define an empty Array and populate it with ValidationResult objects as your validator encounters errors.
You can use the StringValidator class to validate that a string is longer than a minimum length and shorter than a maximum length, but you cannot use it to validate the contents of a string. This example creates a simple validator class that determines if a person is more than 18 years old based on their year of birth.
This validator extends the Validator base class, as the following example shows:
package myValidators
{
import mx.validators.Validator;
import mx.validators.ValidationResult;
public class AgeValidator extends Validator {
// Define Array for the return value of doValidation().
private var results:Array;
// Constructor.
public function AgeValidator() {
// Call base class constructor.
super();
}
// Define the doValidation() method.
override protected function doValidation(value:Object):Array {
// Convert value to a Number.
var inputValue:Number = Number(value);
// Clear results Array.
results = [];
// Call base class doValidation().
results = super.doValidation(value);
// Return if there are errors.
if (results.length > 0)
return results;
// Create a variable and initialize it to the current date.
var currentYear:Date = new Date();
// If input value is not a number, or contains no value,
// issue a validation error.
if (isNaN(inputValue) || !value )
{
results.push(new ValidationResult(true, null, "NaN",
"You must enter a year."));
return results;
}
// If calculated age is less than 18, issue a validation error.
if ((currentYear.getFullYear() - inputValue) < 18) {
results.push(new ValidationResult(true, null, "tooYoung",
"You must be 18."));
return results;
}
return results;
}
}
}
This example first defines a public constructor that calls super() to invoke the constructor of its base class. The base class can perform the check to ensure that data was entered into a required field, if you set the required property of the validator to true.
Notice that the second argument of the constructor for the ValidationResult class is null. You use this argument to specify a subfield, if any, of the object being validated that caused the error. When you are validating a single field, you can omit this argument. For an example that validates multiple fields, see Example: Validating multiple fields.
You can use this validator in your Flex application, as the following example shows:
<?xml version="1.0" ?>
<!-- createcomps_validators/MainAgeValidator.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"
xmlns:MyComp="myValidators.*">
<fx:Declarations>
<MyComp:AgeValidator id="ageV"
required="true"
source="{birthYear}"
property="text" />
</fx:Declarations>
<s:Form >
<s:FormItem label="Enter birth year: ">
<s:TextInput id="birthYear"/>
</s:FormItem>
<s:FormItem label="Enter birth year: ">
<s:Button label="Submit"/>
</s:FormItem>
</s:Form>
</s:Application>
The package statement for your custom validator specifies that you should deploy it in a directory called myValidators. In the previous example, you place it in the subdirectory of the directory that contains your Flex application. Therefore, the namespace definition in your Flex application is xmlns:MyComp="myValidators.*". For more information on deployment, see Component compilation.
A validator can validate more than one field at a time. For example, you could create a custom validator called NameValidator to validate three input controls that represent a person's first, middle, and last names.
To create a validator that examines multiple fields, you can either define properties on the validator that let you specify the multiple input fields, as does the Flex DateValidator class, or you can require that the single item passed to the validator includes all of the fields to be validated.
In the following example, you use a NameValidator that validates an item that contains three fields named first, middle, and last:
<?xml version="1.0" ?>
<!-- createcomps_validators/MainNameValidator.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"
xmlns:MyComp="myValidators.*">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Declarations>
<fx:Model id="person">
<name>
<custName>
<first>{firstInput.text}</first>
<middle>{middleInput.text}</middle>
<last>{lastInput.text}</last>
</custName>
</name>
</fx:Model>
<MyComp:NameValidator id="nameVal"
source="{person}" property="custName"
listener="{firstInput}"/>
</fx:Declarations>
<mx:TextInput id="firstInput"/>
<mx:TextInput id="middleInput"/>
<mx:TextInput id="lastInput"/>
<mx:Button label="Validate"
click="nameVal.validate();"/>
</s:Application>
This validator examines three input fields. You specify firstInput as the validation listener. Therefore, when a validation error occurs, Flex shows a validation error message on the first TextInput control.
You can implement the NameValidator class, as the following example shows:
package myValidators
{
import mx.validators.Validator;
import mx.validators.ValidationResult;
public class NameValidator extends Validator {
// Define Array for the return value of doValidation().
private var results:Array;
public function NameValidator () {
super();
}
override protected function doValidation(value:Object):Array {
var fName:String = value.first;
var mName:String = value.middle;
var lName:String = value.last;
// Clear results Array.
results = [];
// Call base class doValidation().
results = super.doValidation(value);
// Return if there are errors.
if (results.length > 0)
return results;
// Check first name field.
if (fName == "" || fName == null) {
results.push(new ValidationResult(true,
"first", "noFirstName", "No First Name."));
return results;
}
// Check middle name field.
if (mName == "" || mName == null) {
results.push(new ValidationResult(true,
"middle", "noMiddleName", "No Middle Name."));
return results;
}
// Check last name field.
if (lName == "" || lName == null) {
results.push(new ValidationResult(true,
"last", "noLastName", "No Last Name."));
return results;
}
return results;
}
}
}
In this example, because you are using a single validator to validate three subfields of the Object passed to the validator, you include the optional second argument to the constructor for the ValidationResult class to specify the subfield that caused the validation error. This inclusion permits Flex to identify the input component that caused the error, and to highlight that component in the 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.