欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Flex4: How to Use Validator(Part I)

程序员文章站 2022-04-18 13:42:00
...

1. A simple example for static bind validator

<?xml version="1.0" encoding="utf-8"?>
<mx: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"
				minWidth="955" minHeight="600">
	
	<fx:Declarations>
		<mx:StringValidator id="usernameValidator" 
							source="{username}" property="text"/>
		<mx:NumberValidator id="ageValidator" domain="int" 
							maxValue="150" minValue="0" 
							source="{age}" property="text"/>
		<mx:DateValidator id="birthDayValidator" inputFormat="YYYY-MM-DD"
							source="{birthDay}" property="text"/>
	</fx:Declarations>
	
	<fx:Script>
		<![CDATA[
			import mx.controls.Alert;
			import mx.events.ValidationResultEvent;
			import mx.validators.Validator;
			
			private var validateSucceed:Boolean = false;
			
			private function submit():void
			{
				var validationResult:Array = Validator.validateAll([usernameValidator, ageValidator, birthDayValidator]);
				
				if (validationResult.length != 0)
				{
					Alert.show("Validate error!");
				}
				else
				{
					Alert.show("Validate succeed!");
				}
			}
		]]>
	</fx:Script>
	<mx:VBox>
		<mx:Label fontSize="12" paddingLeft="2" paddingTop="2" text="Name"/>
		<mx:TextInput id="username"/>
	</mx:VBox>
	<mx:VBox>
		<mx:Label fontSize="12" paddingLeft="2" paddingTop="2" text="Age"/>
		<mx:TextInput id="age" restrict="0-9" maxChars="3"/>
	</mx:VBox>
	<mx:VBox>
		<mx:Label fontSize="12" paddingLeft="2" paddingTop="2" text="Birth Year"/>
		<mx:TextInput id="birthDay" restrict="0-9\-" maxChars="10"/>
	</mx:VBox>
	
	<mx:VBox>
		<mx:Button id="commitButton" label="Submit" click="submit();"/>
	</mx:VBox>
</mx:Application>

        Comments:

1) Validator are defined in <fx:Declarations> tag.

2) By default, the property 'required' is true, that means the field associated with the validator mustn't be left blank.

3) Validator calls validate() by default when the validated field valueCommit.

4) 'Source' and 'Property' in <mx:XXXValidator> means that the validator is statically bind to the source.property.

 

 

2. A simple example for dynamic bind validator

<?xml version="1.0" encoding="utf-8"?>
<mx: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"
				minWidth="955" minHeight="600" creationComplete="init();">
	
	<fx:Declarations>
		<mx:StringValidator id="usernameValidator"/>
		<mx:NumberValidator id="intValidator" domain="int" 
							maxValue="150" minValue="0"
							valid="handleValidate(event);" invalid="handleValidate(event);"/>
		<mx:DateValidator id="birthDayValidator" inputFormat="YYYY-MM-DD"/>
	</fx:Declarations>
	
	<fx:Script>
		<![CDATA[
			import mx.controls.Alert;
			import mx.events.ValidationResultEvent;
			import mx.validators.Validator;
			
			private var validateSucceed:Boolean = false;
			
			protected function init():void
			{
				usernameValidator.source = username;
				usernameValidator.property = "text";
				
				birthDayValidator.source = birthDay;
				birthDayValidator.property = "text";
			}
			protected function intFocusInHandler(event:FocusEvent):void
			{
				intValidator.source = event.currentTarget;
				intValidator.property = "text";
			}
			protected function handleValidate(event:ValidationResultEvent):void
			{
				if(event.type == ValidationResultEvent.VALID)  
					submitButton.enabled = true;
				else
					submitButton.enabled = false;
			}
			
			private function submit():void
			{
				var validationResult:Array = Validator.validateAll([usernameValidator, birthDayValidator]);
				
				if (validationResult.length != 0)
				{
					Alert.show("Validate error!");
				}
				else
				{
					Alert.show("Validate succeed!");
				}
			}
		]]>
	</fx:Script>
	<mx:VBox>
		<mx:Label fontSize="12" paddingLeft="2" paddingTop="2" text="Name"/>
		<mx:TextInput id="username"/>
	</mx:VBox>
	<mx:VBox>
		<mx:Label fontSize="12" paddingLeft="2" paddingTop="2" text="Age"/>
		<mx:TextInput id="age" restrict="0-9" maxChars="3" focusIn="intFocusInHandler(event);"/>
	</mx:VBox>
	<mx:VBox>
		<mx:Label fontSize="12" paddingLeft="2" paddingTop="2" text="Score"/>
		<mx:TextInput id="score" restrict="0-9" maxChars="3" focusIn="intFocusInHandler(event);"/>
	</mx:VBox>
	<mx:VBox>
		<mx:Label fontSize="12" paddingLeft="2" paddingTop="2" text="Birth Year"/>
		<mx:TextInput id="birthDay" restrict="0-9\-" maxChars="10"/>
	</mx:VBox>
	
	<mx:VBox>
		<mx:Button id="submitButton" label="Submit" click="submit();"/>
	</mx:VBox>
</mx:Application>

  Comments:

1) Method handled defined in property 'valid' and 'invalid' are invoked after validating the source.property associated with the validator.

    We can use this property to enable or disable specific button.

2) The validator comes to effective by default when specific element valueCommit.

3) We can change the source and property in program dynamically so that we can validate a couple of elements with only one single validator.

 

 3. Customize Validator

package view
{
	import mx.validators.ValidationResult;
	import mx.validators.Validator;

	public class CobDateValidator extends Validator
	{
		// Define Array for the return value of doValidation().
		private var results:Array;
		
		// Constructor.
		public function CobDateValidator() {
			// Call base class constructor. 
			super();
		}
		
		// Define the doValidation() method.
		override protected function doValidation(value:Object):Array {

			// Clear results Array.
			results = [];
			
			// Call base class doValidation().
			results = super.doValidation(value);
			// Return if there are errors.
			if (results.length > 0)
				return results;
			
			// If input value contains no value, 
			// issue a validation error.
			if ( !value )
			{
				results.push(new ValidationResult(true, null, "NaN", 
					"You must enter cob date."));
				return results;
			}       
			
			var year:String = (value as String).substr(0, 4);
			var month:String = (value as String).substr(4, 2);
			var day:String = (value as String).substr(6, 2);
			
			var endDate:Date = new Date(year, month, 0);
			var endDay:String = endDate.getDate().toString();
			// If the input day is not the end day of month, issue a validation error.
			if (endDay != day) {
				results.push(new ValidationResult(true, null, "Error", 
					"Incorrect cob date"));
				return results;
			}
			
			return results;
		}
	}
}

 

<?xml version="1.0" encoding="utf-8"?>
<mx: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:ui="view.*"
				minWidth="955" minHeight="600">
	
	<fx:Declarations>
		<ui:CobDateValidator id="cobDateValidator" source="{cobDate}" property="text"/>
	</fx:Declarations>
	
	<fx:Script>
		<![CDATA[
			import mx.controls.Alert;
			import mx.events.ValidationResultEvent;
			import mx.validators.Validator;
			
			private var validateSucceed:Boolean = false;
			
			private function submit():void
			{
				var validationResult:Array = Validator.validateAll([cobDateValidator]);
				
				if (validationResult.length != 0)
				{
					Alert.show("Validate error!");
				}
				else
				{
					Alert.show("Validate succeed!");
				}
			}
		]]>
	</fx:Script>
	<mx:VBox>
		<mx:Label fontSize="12" paddingLeft="2" paddingTop="2" text="COB Date"/>
		<mx:TextInput id="cobDate"/>
	</mx:VBox>
	<mx:VBox>
		<mx:Button id="submitButton" label="Submit" click="submit();"/>
	</mx:VBox>
</mx:Application>

 

Comments:

1) This validator can be used as an enhanced date validator that only the last day of the month is valid.

 

 

Reference Links:

1) http://livedocs.adobe.com/flex/3/html/help.html?content=validators_3.html

 

相关标签: Flex Validator