2013-03-20 67 views
0

我只能验证一个字段。flex:如何验证多个必填字段

<mx:Validator required="true" property="text" source="{name}" valid="vaildator(event)" invalid="vaildator(event)" /> 

感谢

+0

嗯,你只需要添加更多的验证器 – RIAstar 2013-03-20 09:08:40

+0

你必须为每个字段定义一个验证器。您应该查看Validation Giude Line http://livedocs.adobe.com/flex/3/html/help.html?content=validators_2.html。多字段和验证器也是一个很好的例子。 – Panciz 2013-03-20 10:07:42

回答

1

使用Validator.validateAll()函数来获取每个字段的有效性,然后检查返回数组是空的。

<?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"> 
<fx:Declarations> 
    <mx:StringValidator 
     id="svSurname" 
     source="{tiSurname}" 
     property="text" 
     requiredFieldError="Surname is required!" 
     required="true"/> 

    <mx:StringValidator 
     id="svFirstname" 
     source="{tiFirstname}" 
     property="text" 
     requiredFieldError="Firstname is required!" 
     required="true"/> 

    <mx:NumberValidator 
     id="nvAge" 
     source="{tiAge}" 
     property="text" 
     lowerThanMinError="Only after 18 years old" 
     minValue="18" 
     requiredFieldError="Age is required!" 
     required="true"/> 

</fx:Declarations> 

<fx:Script> 
    <![CDATA[ 
     import mx.controls.Alert; 
     import mx.validators.Validator; 
     private function onBtnEnter():void 
     { 
      var validationResult:Array = Validator.validateAll([svSurname, svFirstname, nvAge]); 

      if (validationResult.length == 0) 
       Alert.show("All right!"); 
      else 
       Alert.show("You have an error!"); 
     } 
    ]]> 
</fx:Script> 

<s:VGroup x="10" y="10" width="250" height="150"> 

    <s:HGroup width="100%" verticalAlign="bottom"> 
     <s:Label text="Surname*" width="120" textAlign="right"/> 
     <s:TextInput id="tiSurname" width="120"/> 
    </s:HGroup> 

    <s:HGroup width="100%" verticalAlign="bottom"> 
     <s:Label text="Firstname*" width="120" textAlign="right"/> 
     <s:TextInput id="tiFirstname" width="120"/> 
    </s:HGroup> 

    <s:HGroup width="100%" verticalAlign="bottom"> 
     <s:Label text="Age*" width="120" textAlign="right"/> 
     <s:TextInput id="tiAge" width="120"/> 
    </s:HGroup> 

    <s:HGroup horizontalAlign="center" width="100%" height="40"> 
     <s:Button id="btnEnter" label="Send" click="onBtnEnter()"/> 
    </s:HGroup> 

</s:VGroup> 
</s:Application>