首先设置用户名为必填 设置属性required="true"
<mx:FormItem label="用户名" required="true" width="{bfb}">
<s:TextInput id="txtUser" width="{bfb}"/>
</mx:FormItem>
然后添加
<mx:StringValidator id="user_stringValidator" source="{txtUser}" property="text" requiredFieldError="用户名必填" minLength="2">
</mx:StringValidator>
这样就可以验证了,但验证失败后不执行添加事件,需要再添加如下代码:
[Bindable]
private var validatorArr:Array;
protected function titlewindow1_creationCompleteHandler(event:FlexEvent):void
{
validatorArr=new Array();
validatorArr.push(user_stringValidator);
}
在保存的时候
protected function btnOk_clickHandler(event:MouseEvent):void
{
var validatorErrorArr:Array=Validator.validateAll(validatorArr);
var isTrue:Boolean=validatorErrorArr.length==0;
if(isTrue){
user.username=txtUser.text;
user.password=txtPass.text;
userAction.save.send();
}else{
var err:ValidationResultEvent;
var errorMessageArr:Array=[];
for each(err in validatorErrorArr ){
var errField:String=FormItem(err.currentTarget.source.parent).label;
errorMessageArr.push(errField+":"+err.message);
}
Alert.show(errorMessageArr.join("\n\n"),"验证失败",Alert.OK);
}
}要验证时候成功,如果失败,打印验证的错误信息。