Flex4: How to Use Validator(Part I)

阅读更多

1. A simple example for static bind validator



	
	
		
		
		
	
	
	
		
	
	
		
		
	
	
		
		
	
	
		
		
	
	
	
		
	

        Comments:

1) Validator are defined in 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 means that the validator is statically bind to the source.property.

 

 

2. A simple example for dynamic bind validator



	
	
		
		
		
	
	
	
		
	
	
		
		
	
	
		
		
	
	
		
		
	
	
		
		
	
	
	
		
	

  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;
		}
	}
}

 



	
	
		
	
	
	
		
	
	
		
		
	
	
		
	

 

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)