动作脚本3对空值进行NumericStepper验证

时间:2015-07-23 12:05:52

标签: actionscript-3 validation flex actionscript flex3

我有一个简单的NumericStepper,如下所示:

<mx:NumericStepper id="nsPort"
minimum="0"
maximum="65535"
stepSize="1"
value="{PORT_DEFAULT}"/>

我为它写了一个验证器(它没有像我期望的那样工作):

<mx:NumberValidator
required="true"
source="{nsPort}"
property="value"/>

但是,每次我没有在NumericStepper中输入任何东西时,它会传递零,而不是NULL或其他东西,这是......好......一个有效的值。我怀疑这是故意的。那么,如何在NumbericStepper中使空值无效? 请注意,我仅限于动作脚本的第3版。

1 个答案:

答案 0 :(得分:1)

来自https://flexscript.wordpress.com/2008/09/22/flex-creating-custom-validators/的示例代码库,稍作修改:

package flexScript
{
     import mx.validators.ValidationResult;
     import mx.validators.Validator;

 //Class should extend mx.validators.Validator
 public class NumericStepperValidator extends Validator {

        public function NumericStepperValidator() {
            // Call base class constructor.
            super();
        }

        // Class should override the doValidation() method.
        //doValidation method should accept an Object type parameter
        override protected function doValidation(value:Object):Array {
            // create an array to return.
            var ValidatorResults:Array = new Array();
            // Call base class doValidation().
            ValidatorResults = super.doValidation(value);       
            // Return if there are errors.
            if (ValidatorResults.length > 0)
                return ValidatorResults;

            if (String(value).length == 0)
             return ValidatorResults;
            if ( value == 0)//as your required.
             return ValidatorResults;

               var RegPattern:RegExp = /\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/; //Change to your customize regExpression
            var a:Array = RegPattern.exec(String(value));
               if (a == null)
               {
                ValidatorResults.push(new ValidationResult(true, null, "NumbericStepper Error","You must enter an Number"));
                return ValidatorResults;
               }
             return ValidatorResults;
        }
    }
}

<flexScript:NumbericStepperValidator source="{{nsPort}}" property="number"/>