Validating integers using the NumberValidator class

by Peter deHaan on August 30, 2008

in NumberValidator, Validators

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"?>
<!-- http://blog.flexexamples.com/2008/08/30/validating-integers-using-the-numbervalidator-class/ -->
<mx:Application name="NumberValidator_domain_test"
        xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white">
 
    <mx:Script>
        <![CDATA[
            import mx.controls.Alert;
            import mx.events.ValidationResultEvent;
 
            private function numberValidator_invalid(evt:ValidationResultEvent):void {
                Alert.show(evt.message);
            }
 
            private function numberValidator_valid(evt:ValidationResultEvent):void {
                Alert.show(evt.type);
            }
        ]]>
    </mx:Script>
 
    <mx:NumberValidator id="numberValidator"
            domain="{comboBox.selectedItem}"
            source="{textInput}"
            property="text"
            trigger="{button}"
            triggerEvent="click"
            invalid="numberValidator_invalid(event);"
            valid="numberValidator_valid(event);" />
 
    <mx:ApplicationControlBar dock="true">
        <mx:Form styleName="plain">
            <mx:FormItem label="domain:">
                <mx:ComboBox id="comboBox"
                        dataProvider="[real,int]" />
            </mx:FormItem>
        </mx:Form>
    </mx:ApplicationControlBar>
 
    <mx:Form defaultButton="{button}">
        <mx:FormItem direction="horizontal">
            <mx:TextInput id="textInput"
                    restrict="0-9\\.\\-"
                    maxChars="10" />
            <mx:Button id="button"
                    label="validate" />
        </mx:FormItem>
    </mx:Form>
 
</mx:Application>

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"?>
<!-- http://blog.flexexamples.com/2008/08/30/validating-integers-using-the-numbervalidator-class/ -->
<mx:Application name="NumberValidator_domain_test"
        xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white"
        initialize="init();">
 
    <mx:Script>
        <![CDATA[
            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.events.ValidationResultEvent;
            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;
                numberValidator.property = "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:";
                formItem1.addChild(comboBox);
 
                var form1:Form = new Form();
                form1.styleName = "plain";
                form1.addChild(formItem1);
 
                var appControlBar:ApplicationControlBar;
                appControlBar = new ApplicationControlBar();
                appControlBar.dock = true;
                appControlBar.addChild(form1);
                addChildAt(appControlBar, 0);
 
                var formItem2:FormItem = new FormItem();
                formItem2.direction = FormItemDirection.HORIZONTAL;
                formItem2.addChild(textInput);
                formItem2.addChild(button);
 
                var form2:Form = new Form();
                form2.defaultButton = button;
                form2.addChild(formItem2);
                addChild(form2);
            }
 
            private function comboBox_change(evt:Event):void {
                numberValidator.domain = comboBox.selectedItem.toString();
            }
 
            private function numberValidator_invalid(evt:ValidationResultEvent):void {
                Alert.show(evt.message);
            }
 
            private function numberValidator_valid(evt:ValidationResultEvent):void {
                Alert.show(evt.type);
            }
        ]]>
    </mx:Script>
 
</mx:Application>

{ 13 comments… read them below or add one }

1 peterd September 12, 2008 at 8:08 am

Geert,

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

Peter

Reply

2 Geert September 12, 2008 at 8:00 am

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)

Bye

Reply

3 Geert September 17, 2008 at 6:16 am

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.

Bye

Reply

4 Elextra December 15, 2008 at 3:36 am

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?
Thanks

Reply

5 Elextra December 15, 2008 at 3:38 am

Sorry, code was swollen by the blog parser

<mx:TextInput id="someid" restrict="(^[1-9])+[0-9]+"/>

Reply

6 Peter deHaan December 15, 2008 at 8:33 am

Elextra,

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

http://livedocs.adobe.com/flex/3/langref/mx/controls/TextInput.html#restrict
http://livedocs.adobe.com/flex/3/langref/flash/text/TextField.html#restrict

You could try listening for the change and/or textInput events and then calling a custom RegExpValidator: http://livedocs.adobe.com/flex/3/langref/mx/validators/RegExpValidator.html

Peter

Reply

7 JabbyPanda November 19, 2009 at 3:50 am

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”

Reply

8 Sameera Sandaruwan November 23, 2009 at 11:56 pm

Steps to reproduce:
1. TextInput creates dynamically

textInputBox = new MyTextInput;
 
textInputBox.restrict = "0-9.";
textInputBox.maxChars = 24;
amountValidator = new NumberValidator();
amountValidator.source = textInputBox;
amountValidator.property = "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

Reply

9 Usman Ajmal December 26, 2009 at 4:13 am

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?

Reply

10 Peter deHaan December 26, 2009 at 8:27 am

@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="http://www.adobe.com/2006/mxml">
 
    <mx:Script>
        <![CDATA[
            import mx.controls.Alert;
            import mx.events.ValidationResultEvent;
 
            private function validateForm():void {
                var result:ValidationResultEvent = numVal.validate();
 
                switch (result.type) {
                    case ValidationResultEvent.INVALID:
                        Alert.show(result.message, "Error!");
                        break;
                    case ValidationResultEvent.VALID:
                        Alert.show("Thanks!");
                        break;
                }
            }
        ]]>
    </mx:Script>
 
    <mx:NumberValidator id="numVal" 
            source="{lst}" 
            property="selectedIndex"
            minValue="0"
            lowerThanMinError="Please select an item from the list." />
 
    <mx:Form defaultButton="{btn}">
        <mx:FormItem label="Products:">
            <mx:List id="lst" 
                    allowMultipleSelection="true"
                    width="100">
                <mx:dataProvider>
                    <mx:ArrayCollection source="[one,two,three,four,five,six,seven,eight,nine,ten]" />
                </mx:dataProvider>
            </mx:List>
        </mx:FormItem>
        <mx:FormItem>
            <mx:Button id="btn"
                    label="Submit"
                    click="validateForm();" />
        </mx:FormItem>
    </mx:Form>
 
</mx:Application>

Reply

11 Usman Ajmal December 26, 2009 at 9:54 am

Thanks a lot Peter. I already managed to develop what you just suggested. However, I did not know about mx.events.ValidationResultEvent. Thanks for letting me know about it and answering me. :)

Reply

12 Sameera Sandaruwan February 3, 2010 at 3:10 am

Do you anyone can help me to change, theme color when validations active(red color), i need to change some other, but still working on.

Reply

13 Peter deHaan February 3, 2010 at 8:19 am

@Sameera Sandaruwan,

Try setting the errorColor style; “Customizing a Flex TextInput control’s error color”.

Peter

Reply

Leave a Comment

Sorry, this blog is terrible at eating HTML comments.
If you're pasting any HTML/XML/MXML code, you need to convert your < characters to &lt; and your > characters to &gt; .

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Anti-Spam Protection by WP-SpamFree

Previous post:

Next post: