flex:如何验证多个必填字段

时间:2013-03-20 08:28:34

标签: flex validation required

我只能验证一件。

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

感谢

1 个答案:

答案 0 :(得分: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>