30
Aug
08

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.

View MXML

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

View MXML

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

6 Responses to “Validating integers using the NumberValidator class”


  1. 1 Geert Sep 12th, 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

  2. 2 peterd Sep 12th, 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

  3. 3 Geert Sep 17th, 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

  4. 4 Elextra Dec 15th, 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

  5. 5 Elextra Dec 15th, 2008 at 3:38 am

    Sorry, code was swollen by the blog parser

    <mx:TextInput id="someid" restrict="(^[1-9])+[0-9]+"/>
    
  6. 6 Peter deHaan Dec 15th, 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

Leave a Reply

This blog is terrible at eating HTML tags. If you plan on posting code/XML, please escape your "<" characters as "&lt;" and your ">" characters as "&gt;".




Badge Farm

  • Powered by Redoable 1.2
  • Cornify
  • Feeds burnt by Feedburner
  • Feed