Posts Tagged ‘Flex 4’

Flex 4 Custom Validators in 5 Minutes

October 12th, 2010 No comments

Flex out of the box provides several validators that can be used for validating user input. These validators are bundled in the mx.validator package. However, there will be times where we might need to write our own validators. In this post, I will create a custom validator that can be used for validating a combo box.

Creating a custom validator involves extending the mx.validators.Validator class and overriding its doValidation method.

package validators
	import mx.validators.Validator;

	public class ComboBoxValidator extends Validator
		public function ComboBoxValidator()
		override protected function doValidation(value:Object):Array 
			return null;

The doValidator method holds the logic for validating the passed in value. This value is the data entry control’s property and is passed in by Flex. For our combo box validation we will be using its selectedItem property. Any validation errors will be reported as instances of mx.validators.ValidationResult. With this information in hand, here is the complete implementation of the doValidation method.

override protected function doValidation(value:Object):Array 
		var resultArray:Array = [];
		if(value == null) 
			resultArray.push(new ValidationResult(true, "", "", "Validation Failed"));
		return resultArray;

And here is the MXML application that uses the custom validator.

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="" 
			   minWidth="955" minHeight="600">
			import mx.validators.Validator;

		<s:ArrayCollection id="countries">
		<validators:ComboBoxValidator id="cmbCountryValidator" source="{cmbCountry}" property="selectedItem" />
		<s:VerticalLayout paddingLeft="20" paddingTop="20" />

	<s:ComboBox id="cmbCountry" dataProvider="{countries}" focusOut="Validator.validateAll( [cmbCountryValidator] )" width="200" />
	<s:TextInput width="200" />

Categories: Flex Tags: , ,