Using Validators in Adobe Flex

Posted By : Ankush Gulati | 09-Apr-2013

It's always useful to check the validity of data before submission. Flex provides several built-in validators for this purpose such as: Credit card numbers, Dates, e-mail addresses, Phone numbers, regular expressions and Zip code etc. All standard validator components inherits from the base of mx.Validators.Validator class. User can define these validators in MXML or ActionScript by following syntax:

1. In MXML: User can define a validator by using mx:validatorName tag and specifying the "source" and "property" elements. Like, the following code snippet.





  

The above in-built validator puts a validation on textInput that it should only contain a valid phone number, failing which, the color of TextInput becomes red indicating an error.

source: represents the object which is to be validated.

property: represents the name of property of source to be validated. (like "text" property in above case).

2. In ActionScript:

                	
		
	

        

The above code snippet automatically places a validator on "TextInput2", once it's created. and it checks for validation as soon as this TextInput looses focus. However, there are cases when user may require to validate on particular event like click of a button. In these cases, Validator.validate() function can be used on Button click event.

3. Creating Custom Validators: There are scenarios where user might need to create and use custom validators in flex. This process is also simple. User just need to keep in mind the following points:
a) Create a class which extends mx.Validators.Validator
b) This class must override the default "doValidation()" method.
c) The doValidation() method should accept a parameter of type Object.
d) This method should return an Array.
Following is the code snippet used to create a custom validator which matches two password fields for equality. The CustomValidator.as class:

                package
{
	import mx.validators.ValidationResult;
	import mx.validators.Validator;
	
	public class CustomValidator extends Validator
	{
		public var targetVal:Object;
		public var errorMessage:String = "Value don't match. Check Again. ";
		
		public function CustomValidator()
		{
			super();
		}
		
		override protected function doValidation(value:Object):Array {
			var results:Array = [];
			var srcVal:Object = this.getValueFromSource();
			
			if (srcVal != targetVal) {
				results.push(new ValidationResult(true, null, "Match",errorMessage));
			}
			return results;	
		}
	}
}
        

Below code is for use in mxml:

                
        

where "pwdReType" and "pwdMain" are the id's of TextInput's to be compared.


Hope it helps!!

Ankush Gulati

[email protected]

About Author

Author Image
Ankush Gulati

Request for Proposal

Name is required

Comment is required

Sending message..