Flex2开发项目中经常需要验证用户输入,Flex2自身为我们提供丰富的组件。
下面的例子我们实现了如下一些特性:
1)数据集中验证
2)定位光标到第一个验证失败的位置
3)错误提示中中文显示的CSS
<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:local="*" creationComplete="initValidatorArray();" width="402" height="152">
<mx:Script>
<![CDATA[
import mx.events.ValidationResultEvent;
import mx.core.UIComponent;
import mx.controls.Alert;
import mx.validators.*;
private var myValidators:Array;
private function initValidatorArray():void {
myValidators=[zipV, pnV];
}
//按钮事件,检测通过执行操作
private function btnValidate_Click(event:Event):void{
var validatorResults:Array = mx.validators.Validator.validateAll(myValidators);
//长度为0表示所有验证通过
if(validatorResults.length == 0){
mx.controls.Alert.show("Validate OK!");
}else{
//将光标定位到第一个错误
var v:ValidationResultEvent = validatorResults[0] as ValidationResultEvent;
(v.target.source as UIComponent).setFocus();
}
}
]]>
</mx:Script>
<!--如果你要在验证错误提示中显示中文,使用这个改变字体大小!-->
<mx:Style>
.errorTip {fontFamily:"simsun"; fontSize:"12"}
</mx:Style>
<mx:ZipCodeValidator id="zipV" source="{zipCodeInput}" property="text" requiredFieldError="邮编必须填写"/>
<mx:PhoneNumberValidator id="pnV" source ="{phoneNumberInput}" property="text" />
<mx:Form x="24" y="24">
<mx:FormItem label="zip Code:" required="true">
<mx:TextInput id="zipCodeInput"/>
</mx:FormItem>
<mx:FormItem label="phone Number:" required="true">
<mx:TextInput id="phoneNumberInput"/>
</mx:FormItem>
</mx:Form>
<mx:Button label="Validate" click="btnValidate_Click(event)"/>
</mx:Application>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:local="*" creationComplete="initValidatorArray();" width="402" height="152">
<mx:Script>
<![CDATA[
import mx.events.ValidationResultEvent;
import mx.core.UIComponent;
import mx.controls.Alert;
import mx.validators.*;
private var myValidators:Array;
private function initValidatorArray():void {
myValidators=[zipV, pnV];
}
//按钮事件,检测通过执行操作
private function btnValidate_Click(event:Event):void{
var validatorResults:Array = mx.validators.Validator.validateAll(myValidators);
//长度为0表示所有验证通过
if(validatorResults.length == 0){
mx.controls.Alert.show("Validate OK!");
}else{
//将光标定位到第一个错误
var v:ValidationResultEvent = validatorResults[0] as ValidationResultEvent;
(v.target.source as UIComponent).setFocus();
}
}
]]>
</mx:Script>
<!--如果你要在验证错误提示中显示中文,使用这个改变字体大小!-->
<mx:Style>
.errorTip {fontFamily:"simsun"; fontSize:"12"}
</mx:Style>
<mx:ZipCodeValidator id="zipV" source="{zipCodeInput}" property="text" requiredFieldError="邮编必须填写"/>
<mx:PhoneNumberValidator id="pnV" source ="{phoneNumberInput}" property="text" />
<mx:Form x="24" y="24">
<mx:FormItem label="zip Code:" required="true">
<mx:TextInput id="zipCodeInput"/>
</mx:FormItem>
<mx:FormItem label="phone Number:" required="true">
<mx:TextInput id="phoneNumberInput"/>
</mx:FormItem>
</mx:Form>
<mx:Button label="Validate" click="btnValidate_Click(event)"/>
</mx:Application>
示例: