<myStringValidator.as>
package myComponent
{
import mx.validators.StringValidator;
import mx.validators.ValidationResult;
//扩展字符串校验类:增加英文数字校验功能
public class MyStringValidator extends StringValidator
{
public function MyStringValidator()
{
super();
}
//自定义属性,校验出错时的出错信息
[Property("typeError")]
private var _myTypeError:String;
public function get typeError():String
{
return _myTypeError;
}
public function set typeError(value:String):void
{
_myTypeError = value;
}
/**校验函数:必须重载父类的doValidation函数
*/
override protected function doValidation(value:Object):Array{
//定义返回值,并初始化
var results:Array;
results=[];
/*首先执行父类的基本数据校验,得到校验结果
如果校验未通过,则中止继续执行*/
results=super.doValidation(value);
if(results.length>0)
return results;
//如果校验通过,则执行自定义的校验功能
//利用正则功能校验输入是否为英文或数字
var regExp1:RegExp=new RegExp("[^A-Za-z0-9]");
//校验
if(regExp1.test(value.toString()))
{
//校验未通过,则生成一个校验结果
var vr:ValidationResult=new ValidationResult(true,null,"typeError",typeError);
//把校验结果加入返回值数组中
results.push(vr);
}
//返回校验结果
return results;
}
}
}
<testValidator.mxml>:
<?xml version="1.0" encoding="utf-8"?>
<s: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"
xmlns:myComponent="myComponent.*"
creationComplete="init()">
<fx:Style>
@namespace s "library://ns.adobe.com/flex/spark";
@namespace mx "library://ns.adobe.com/flex/mx";
@namespace myComponent "myComponent.*";
</fx:Style>
<fx:Script>
<![CDATA[
import mx.core.UIComponent;
import mx.events.ValidationResultEvent;
import mx.validators.ValidationResult;
import mx.controls.Alert;
import myComponent.AsComponent;
public function init():void{
var myCom:AsComponent=new AsComponent("标签","按钮");
//myPanel.addChild(myCom);
myPanel.addElement(myCom);
}
private function doIt(event:Event):void{
var vEvent:ValidationResultEvent;
vEvent=vUserName.validate();
if(vEvent.type==ValidationResultEvent.INVALID)
{
(vEvent.target.source as UIComponent).setFocus();
}
else{
Alert.show("用户名没有问题");
}
}
]]>
</fx:Script>
<fx:Declarations>
<myComponent:MyStringValidator id="vUserName"
source="{txtUserName}"
property="text"
minLength="8"
maxLength="20"
required="true"
requiredFieldError="请输入用户名"
tooLongError="用户名太长了,最长20位"
tooShortError="用户名太短了,最短8位"
typeError="只能输入英文和数字"
/>
</fx:Declarations>
<s:Panel x="119" y="127" width="250" height="200" id="myPanel">
</s:Panel>
<s:TextInput x="84" y="37" id="txtUserName"/>
<s:Button x="234" y="37" label="确定" click="doIt(event)"/>
</s:Application>