`
DavyJones2010
  • 浏览: 154246 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

Flex4: How to Use Validator(Part I)

    博客分类:
  • Flex
阅读更多

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

 

分享到:
评论

相关推荐

    how to use spring validator

    how to use spring validator

    hibernate-validator 5.3.5.Final jar

    hibernate-validator 5.3.5.Final jar包 ;desc:if you want validator your project

    javax.net.ssl.SSLHandshakeException: sun.security.validator 问题解决,与环境有关

    在本例中,错误信息中包含“sun.security.validator”,这可能暗示了证书验证的问题。 首先,我们需要理解SSL/TLS握手过程。它涉及几个步骤,包括身份验证、密钥交换和协议协商。在这个过程中,客户端会验证服务器...

    async-validator:验证表单异步

    一种变体安装npm i async-validator用法基本用法包括定义一个描述符,将其分配给一个模式,并将要验证的对象以及一个回调函数传递给该模式的validate方法: import Schema from 'async-validator' ;const ...

    Async Validator 异步验证使用说明

    Async Validator 异步验证使用说明 Async Validator 是一个异步验证的库,需要传入要验证的数据和验证规则。下面是 Async Validator 异步验证使用说明的详细知识点: 一、Async Validator 的基本概念 Async ...

    fluent-validator-1.0.6-API文档-中文版.zip

    赠送jar包:fluent-validator-1.0.6.jar; 赠送原API文档:fluent-validator-1.0.6-javadoc.jar; 赠送源代码:fluent-validator-1.0.6-sources.jar; 包含翻译后的API文档:fluent-validator-1.0.6-javadoc-API...

    Flex from_validator_表单验证

    本教程将详细讲解"Flex from_validator_表单验证"的相关知识点,帮助你理解和掌握表单验证的基本流程和处理方法。 一、表单验证简介 表单验证主要在用户填写并提交表单时进行,通过验证用户的输入,防止无效数据或...

    fluent-validator-1.0.6-API文档-中英对照版.zip

    赠送jar包:fluent-validator-1.0.6.jar; 赠送原API文档:fluent-validator-1.0.6-javadoc.jar; 赠送源代码:fluent-validator-1.0.6-sources.jar; 包含翻译后的API文档:fluent-validator-1.0.6-javadoc-API...

    XML::Validator::Schema-开源

    XML::Validator::Schema 是一个基于 Perl 语言的开源模块,其主要功能是验证 XML 文档是否符合 W3C XML Schema 的规范。W3C XML Schema(通常简称为 XML Schema)是一种用于定义 XML 文档结构和数据类型的语言,它...

    hibernate-validator-6.0.8

    《Hibernate Validator 6.0.8:数据验证的利器》 Hibernate Validator,作为Java Bean Validation规范的实现,是处理数据验证的重要工具。6.0.8版本是该框架的一个稳定版本,提供了诸多改进和增强,使得开发者在...

    common-validator

    **通用验证器(common-validator)** 在Web开发中,数据验证是不可或缺的一环,尤其是在客户端进行JavaScript编程时。`common-validator`是一款专为JavaScript设计的轻量级验证框架,旨在简化和增强网页表单数据的...

    hibernate-validator-4.1.0.Final.rar

    《Hibernate Validator 4.1.0.Final:深入理解企业级数据验证框架》 Hibernate Validator是Hibernate项目的一个重要组成部分,它是一个基于JSR-303(Bean Validation)规范的实现,提供了强大的Java Bean数据验证...

    bootstrapvalidator

    4. **自定义验证**:除了预设的验证规则外,BootstrapValidator还允许你创建自定义验证器。通过`.addValidator()`方法,你可以定义一个新的验证函数,并指定错误消息。 5. **反馈样式**:BootstrapValidator利用...

    html-validator:一个使用validator.w3.orgnu验证html的Node.js模块

    html-validator ...要求Node&gt; = 10.20.1(对于较旧版本...$ npm i html-validator 用法 创建一个选项对象。 format这是返回数据的格式。 对于W3C,它支持json(默认值),html,xhtml,xml,gnu和text;对于WHATWG,它

    hibernate-validator-6.0.18.Final-sources.jar

    java运行依赖jar包

    eslint-plugin-json-schema-validator:使用JSON Schema Validator验证数据的ESLint插件

    是ESLint插件,可使用JSON Schema Validator验证数据。 :name_badge: 特征该ESLint插件使用JSON Schema验证 , , , , 和JavaScript。 :open_book: 文献资料参见。 :optical_disk: 安装npm install --save-dev ...

    ngx-validator:Angular 7+ Validator,一个易于处理且自动处理验证消息的库

    import { NgxValidatorModule, ValidationFeedbackStrategyBuilder } from '@why520crazy/ngx-validator'; @NgModule({ imports: [ CommonModule, NgxValidatorModule.forRoot({ validationFe

    hibernate validator jsr303

    4. 执行验证:使用`Validator`对象的`validate()`方法对对象进行验证,并处理验证结果。 **应用场景** Hibernate Validator广泛应用于Web应用、服务端API验证、ORM框架(如Hibernate)的数据验证等场景。通过它的...

    hibernate-validator官方文档(中、英)

    Hibernate Validator 是一个强大的Java Bean验证框架,它是JSR 303/349和JSR 380规范的参考实现。这个压缩包包含了官方文档的中文和英文版本,对于学习和理解Hibernate Validator的使用非常有帮助。下面将详细阐述 ...

    Validator

    &lt;script src="path/to/validator.min.js"&gt; 提交 var form = document.getElementById('myForm'); var validator = new Validator(form, { email: {required: true, email: true}, password: {...

Global site tag (gtag.js) - Google Analytics