Validating integers using the NumberValidator class

The following example shows how you can validate a number as an integer or real (floating point) number by setting the domain property on a NumberValidator instance.

Full code after the jump.

<?xml version="1.0" encoding="utf-8"?>
<!-- -->
<mx:Application name="NumberValidator_domain_test"
            import mx.controls.Alert;
            private function numberValidator_invalid(evt:ValidationResultEvent):void {
            private function numberValidator_valid(evt:ValidationResultEvent):void {
    <mx:NumberValidator id="numberValidator"
            valid="numberValidator_valid(event);" />
    <mx:ApplicationControlBar dock="true">
        <mx:Form styleName="plain">
            <mx:FormItem label="domain:">
                <mx:ComboBox id="comboBox"
                        dataProvider="[real,int]" />
    <mx:Form defaultButton="{button}">
        <mx:FormItem direction="horizontal">
            <mx:TextInput id="textInput"
                    maxChars="10" />
            <mx:Button id="button"
                    label="validate" />

View source is enabled in the following example.

Due to popular demand, here is the “same” example in a more ActionScript friendly format:

<?xml version="1.0" encoding="utf-8"?>
<!-- -->
<mx:Application name="NumberValidator_domain_test"
            import mx.containers.ApplicationControlBar;
            import mx.containers.Form;
            import mx.containers.FormItem;
            import mx.containers.FormItemDirection;
            import mx.controls.Alert;
            import mx.controls.Button;
            import mx.controls.ComboBox;
            import mx.controls.TextInput;
            import mx.validators.NumberValidator;
            private var numberValidator:NumberValidator;
            private var comboBox:ComboBox;
            private var textInput:TextInput;
            private var button:Button;
            private function init():void {
                comboBox = new ComboBox();
                comboBox.dataProvider = ["real", "int"];
                comboBox.selectedIndex = 0;
                comboBox.addEventListener(Event.CHANGE, comboBox_change);
                textInput = new TextInput();
                textInput.restrict = "0-9\\.\\-";
                textInput.maxChars = 10;
                button = new Button();
                button.label = "validate";
                numberValidator = new NumberValidator();
                numberValidator.domain = comboBox.selectedItem.toString();
                numberValidator.source = textInput;
       = "text";
                numberValidator.trigger = button;
                numberValidator.triggerEvent = MouseEvent.CLICK;
                numberValidator.addEventListener(ValidationResultEvent.INVALID, numberValidator_invalid);
                numberValidator.addEventListener(ValidationResultEvent.VALID, numberValidator_valid);
                var formItem1:FormItem = new FormItem();
                formItem1.label = "domain:";
                var form1:Form = new Form();
                form1.styleName = "plain";
                var appControlBar:ApplicationControlBar;
                appControlBar = new ApplicationControlBar();
                appControlBar.dock = true;
                addChildAt(appControlBar, 0);
                var formItem2:FormItem = new FormItem();
                formItem2.direction = FormItemDirection.HORIZONTAL;
                var form2:Form = new Form();
                form2.defaultButton = button;
            private function comboBox_change(evt:Event):void {
                numberValidator.domain = comboBox.selectedItem.toString();
            private function numberValidator_invalid(evt:ValidationResultEvent):void {
            private function numberValidator_valid(evt:ValidationResultEvent):void {

13 thoughts on “Validating integers using the NumberValidator class

  1. Geert,

    Thanks. Yeah, somewhere between WordPress and my current theme, the single backslashes need to get doubled up. I fixed the entry above.


  2. Hi Peter,
    While it is probably in your real code (since it works fine) it’s not visible in the grey code boxes that the lines where you restrict the acceptable characters to digits, a period and a minus sign should read:

    In MXML: restrict = "0-9.\-";
    In AS: restrict = "0-9.\\-";

    Since the ‘-‘ is a character with a special meaning (=to specify a range as you can see in 0-9) it has to be prefixed with a backslash in MXML and two backslashes in AS. (cf. the documentation of TextInput)


  3. Peter,

    1) In actionscript it should read

    restrict = "0-9.-";

    so, I guess that means you have to write it with 4 backslashes to make WordPress show two of them.

    2) I think there’s no need to prefix the period with a backslash as it has no special meaning.


  4. Hi guys,

    I was wondering if I could use restrict to put in some real regex stuff.
    Example: Can I put in a regex of this kind /(^[1-9])+[0-9]+/
    Basically, I don’t wanna allow the user to enter 0 as a first digit, but it should be allowed afterward. All data entered should be digits.
    123123 is valid
    012313 is not valid
    323403 is valid

    I dont seem to be able to do that with restrict! My code is:
    –> which basically only allows me to enter open parenthesis ….
    I am clearly doing something wrong?

  5. Elextra,

    The restrict restrict property only accepts “simple” strings, not regular expressions, and it basically matches how the TextField class’s restrict property works.

    You could try listening for the change and/or textInput events and then calling a custom RegExpValidator:


  6. It’s worthy to note that it is more error-proof to use defined constants in static class NumberValidatorDomainType: NumberValidatorDomainType.INT and NumberValidatorDomainType.REAL instead of hardcoded strings “int” and “real”

  7. Steps to reproduce:
    1. TextInput creates dynamically

    textInputBox = new MyTextInput;
    textInputBox.restrict = "0-9.";
    textInputBox.maxChars = 24;
    amountValidator = new NumberValidator();
    amountValidator.source = textInputBox; = "text";
    amountValidator.allowNegative = false;
    amountValidator.domain = "real";
    amountValidator.precision = 4;
    amountValidator.required = false;
    amountValidator.maxValue = 999999999999.9999;
    amountValidator.trigger = textInputBox;
    amountValidator.triggerEvent = Event.CHANGE;
    amountValidator.addEventListener(ValidationResultEvent.VALID, amountValid);
    amountValidator.addEventListener(ValidationResultEvent.INVALID, amountInvalid);
    private function amountValid(event:ValidationResultEvent):void
        valid = true;
        fieldsValidated = true;
    private function amountInvalid(event:ValidationResultEvent):void
        valid = false;
        fieldsValidated = true;

    2. As mention in the creation, when we exceed the limit, it shows error my red color border, and the same time if you delete them by DEL key when it come to the given acceptable limit, automatically become to green soon.
    3. Leave from the field and change values of another textinput(this is just a textinput, this is a form there are some more form elemets), then come back to value exceeded textfield by SHIFT+TABS and remove the additional entered numbers, when you come to green soon your value is accepted.
    4.Now again enter more values and now you are in the warn zone, then leave from the field and do the few changes in other form elements.
    5. Then come back to the value exceeded text filed by MOUSE CLICK, and start delete from DEL, even though you removed additional values, still fields shows that you are in warn zone.

    Actual Results:
    Even when remove additional numbers,still field is Red

    Expected Results:
    if remove additional numbers, field should come its normal status.

    Picture of this issue can be viewed at View Screen Shot

  8. Nice Example but can I user NumberValidator to validate if atleast one item from a list has been selected using, probably, it’s selectedIndices property which is set to NULL at the init() of an application?

    1. @Usman Ajmal,

      Sure. But I’d probably just check that the selectedIndex property isn’t -1, as seen in the following example:

      <?xml version="1.0"?>
      <mx:Application xmlns:mx="">
                  import mx.controls.Alert;
                  private function validateForm():void {
                      var result:ValidationResultEvent = numVal.validate();
                      switch (result.type) {
                          case ValidationResultEvent.INVALID:
                    , "Error!");
                          case ValidationResultEvent.VALID:
          <mx:NumberValidator id="numVal" 
                  lowerThanMinError="Please select an item from the list." />
          <mx:Form defaultButton="{btn}">
              <mx:FormItem label="Products:">
                  <mx:List id="lst" 
                          <mx:ArrayCollection source="[one,two,three,four,five,six,seven,eight,nine,ten]" />
                  <mx:Button id="btn"
                          click="validateForm();" />
  9. Thanks a lot Peter. I already managed to develop what you just suggested. However, I did not know about Thanks for letting me know about it and answering me. :)

Comments are closed.