Archive

Posts Tagged ‘Spark Components’

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()
		{
			super();
		}
		
		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="http://ns.adobe.com/mxml/2009" 
			   xmlns:s="library://ns.adobe.com/flex/spark" 
			   xmlns:mx="library://ns.adobe.com/flex/mx" 
			   xmlns:validators="validators.*"
			   minWidth="955" minHeight="600">
	<fx:Script>
		<![CDATA[
			import mx.validators.Validator;
		]]>
	</fx:Script>

	<fx:Declarations>
		
		<s:ArrayCollection id="countries">
			<s:source>
				<fx:String>Australia</fx:String>
				<fx:String>India</fx:String>
				<fx:String>France</fx:String>
				<fx:String>USA</fx:String>
			</s:source>
		</s:ArrayCollection>
		
		<validators:ComboBoxValidator id="cmbCountryValidator" source="{cmbCountry}" property="selectedItem" />
		
	</fx:Declarations>
	
	<s:layout>
		<s:VerticalLayout paddingLeft="20" paddingTop="20" />
	</s:layout>

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

Categories: Flex Tags: , ,