Flex3 表单验证

设想一个场景:一个表单有多个字段需要验证,当且仅当所有验证都成功时,提交按钮才可用。代码如下:

    test.mxml

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" 
	layout="absolute" creationComplete="init()">
	<mx:Panel width="400" height="300">
		<mx:Form>
			<mx:FormItem label="地址" required="true" >
				<mx:TextInput id="address"  />
			</mx:FormItem>
			<mx:FormItem label="电话"  required="true" >
				<mx:TextInput id="phone" />
			</mx:FormItem>			
		</mx:Form>
		<mx:ControlBar horizontalAlign="right">
			<mx:Button id="submit" label="提交" enabled="false"/>
		</mx:ControlBar>
	</mx:Panel>
	
	<mx:Array id="validators">
		<mx:Validator required="true" requiredFieldError="地址不能为空!" source="{address}" property="text" />
		<mx:Validator required="true" requiredFieldError="电话不能为空!" source="{phone}" property="text" />
	</mx:Array>
	
	<mx:Script>
		<![CDATA[
			private var formValidator:FormValidator=new FormValidator();
		
			private function init():void{
				formValidator.addValidators(validators);
				formValidator.failedCallBack=function():void{
					submit.enabled=false;
				};
				formValidator.passedCallBack=function():void{
					submit.enabled=true;
				};
			}
			
		]]>
	</mx:Script>
</mx:Application>

 FormValidator.as

  

public function addValidator( validator : Validator) : void {
        	if(!validators.contains(validator)){
        			validator.trigger=this;
        			validator.triggerEvent=Event.CHANGE;
        			validator.source.addEventListener(FlexEvent.VALUE_COMMIT,onChange);
        			validator.source.addEventListener(Event.CHANGE,onChange);
        		
        			validator.addEventListener(ValidationResultEvent.INVALID,function(event:ValidationResultEvent):void{
        				voteMap[event.target.source]=false;
        				_failedCallBack();
        			});
        			validator.addEventListener(ValidationResultEvent.VALID,function(event:ValidationResultEvent):void{
        				voteMap[event.target.source]=true;        				
			        	refresh();
        			});
        			validators.addItem(validator);
        	}
}
  private function onChange(event:Event):void{
         dispatchEvent(new Event(Event.CHANGE));
  }

 

    详细代码看附件:)

 

你可能感兴趣的:(xml,Flex,Adobe,actionscript)