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"?> <!-- 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>
Peter deHaan
Peter deHaan currently works for Adobe on the Flex SDK QA team. While not working on Flex, Flash, and ColdFusion applications, Peter enjoys making up bios and writing in 3rd person. Peter's rarely updated blog can be found at blogs.adobe.com/pdehaan/, actionscriptexamples.com, airexamples.com, and coldfusionexamples.com.
-
Add Widgets (Content Sidebar)
This is your Content Sidebar. Edit this content that appears here in the widgets panel by adding or removing widgets in the Content Sidebar area.
13 Responses to Validating integers using the NumberValidator class
Leave a Reply Cancel reply
-
Categories
- Accordion
- AccordionHeader
- ActionScript
- AddChild
- AdvancedDataGrid
- Alert
- alpha
- Animate
- AnimateProperties
- Application
- Application (Spark)
- ArrayCollection
- BarChart
- baseColor
- beta
- beta1
- beta2
- Bitmap
- Bitmap/BitmapData
- BitmapData
- BitmapFill
- BitmapFill (Spark)
- BitmapGraphic
- BitmapImage
- BitmapImage (Spark)
- BitmapImageResizeMode
- Border (Spark)
- BorderContainer (Spark)
- Box
- BuildInfo
- Button
- Button (Spark)
- ButtonBar
- ButtonBar (Spark)
- ByteArray
- Camera
- Charting
- CheckBox
- CheckBox (Spark)
- ClassFactory
- CollectionEvent
- Color
- ColorPicker
- ColorUtil
- ComboBox
- ComboBoxArrowSkin
- Compiler
- Component
- Component (Spark)
- Configuration
- Container
- ContextMenu
- ContextMenuEvent
- ContextMenuItem
- CSSCondition
- CSSSelector
- CSSStyleDeclaration
- CurrencyFormatter
- CursorManager
- Data Binding
- DataGrid
- DataGrid (Spark)
- DataGridColumn
- Date
- DateBase
- DateChooser
- DateField
- DateFormatter
- Debugging
- DefaultComplexItemRenderer
- DefaultTileListEffect
- DropDownList
- DropDownList (Spark)
- DropDownListButtonSkin
- DropDownListSkin
- DropShadowFilter
- E4X
- Effects
- Ellipse
- EmailValidator
- Embed
- Event
- Fade
- FileFilter
- FileReference
- fill
- Filters
- Flash
- Flash Integration
- FlashVars
- Flex 3 SDK
- Flex Builder
- Flex Builder 3
- Flex SDK
- Flex4
- FLVPlayback
- FocusManager
- FontLookup
- Fonts
- Form
- Form (Spark)
- FormHeading (Spark)
- FormItem
- FormItem (Spark)
- Forms
- FTETextField (Spark)
- FullScreen
- FullScreenEvent
- FxAnimateColor
- FxButtonBar
- FxCheckBox
- FXG
- FxHScrollBar
- FxHSlider
- FxList
- FxNumericStepper
- FxRadioButton
- FxRotate3D
- FxScroller
- FxTextArea
- FxTextInput
- FxToggleButton
- FxVScrollBar
- FxVSlider
- getStyleDeclaration()
- GradientEntry
- Graphic (Spark)
- HBox
- HDividedBox
- HGroup (Spark)
- HorizontalLayout
- HorizontalList
- HSBColor (Spark)
- HScrollBar (Spark)
- HSlider
- HSlider (Spark)
- HTML template
- ID3Info
- Image
- Image (Spark)
- ImageSnapshot
- itemRenderer
- JointStyle
- Label
- Label (Spark)
- Legend
- LegendItem
- LigatureLevel
- Line
- LinearGradientStroke
- LineScaleMode
- LinkBar
- LinkButton
- List
- List (Spark)
- Menu
- MenuBar
- Metadata
- MetadataEvent
- Model
- Mouse
- MouseCursor
- MouseEvent
- Move
- Namespace
- NavigatorContent (Spark)
- needsSWF
- NetConnection
- NetStream
- Nightly Builds
- NumberBaseRoundType
- NumberFormatter
- NumberValidator
- NumericCompare
- NumericStepper
- NumericStepper (Spark)
- ObjectProxy
- ObjectUtil
- paddingLeft
- paddingRight
- Panel
- Panel (Spark)
- Parallel
- Path
- PieChart
- PieSeries
- PieSeriesItem
- PopUpAnchor (Spark)
- PopUpButton
- PopUpManager
- ProgrammaticSkin
- ProgressBar
- PropertyChangeEvent
- QName
- RadialGradient
- RadioButton
- RadioButton (Spark)
- RadioButtonGroup
- RadioButtonGroup (Spark)
- Rect
- RegExp
- Regular Expressions
- Repeater
- RichEditableText
- RichText
- RichText (Spark)
- RichTextEditor
- Rotate
- Rotate3D (Spark)
- Scroller (Spark)
- Sequence
- setStyle()
- SimpleText
- SimpleText (Spark)
- skinClass
- Slider
- SliderEvent
- SolidColor
- SolidColorStroke
- Sort
- SortField
- Sound
- SoundEffect
- Spinner (Spark)
- SpriteVisualElement (Spark)
- StageDisplayState
- States
- StringUtil
- StringValidator
- StyleManager
- Styles
- SWFLoader
- SWFObject
- System
- SystemManager
- TabBar
- TabBar (Spark)
- TabNavigator
- TabStopFormat
- Text
- Text Layout Framework (TLF)
- TextArea
- TextArea (Spark)
- TextBox
- TextConverter
- TextEvent
- TextFlow
- TextFlowUtil
- TextFormat
- TextGraphic
- TextInput
- TextInput (Spark)
- TextLayoutFormat
- TextView
- Themes
- TileLayout
- TileList
- TileOrientation
- Timer
- TitleWindow
- TitleWindow (Spark)
- TLF
- ToggleButton (Spark)
- ToggleButtonBar
- ToolTip
- Transition
- Tree
- TruncationOptions
- UIComponent
- UIFTETextField
- Updater
- URLLoader
- URLRequest
- URLUtil
- URLVariables
- ValidationResultEvent
- Validator
- Validators
- VBox
- VDividedBox
- Vector
- VerticalLayout
- VerticalLayout (Spark)
- VGroup (Spark)
- Video
- VideoDisplay
- VideoElement
- VideoElement (Spark)
- VideoEvent
- VideoPlayer (Spark)
- VideoPlayerScrubBar
- ViewStack
- VScrollBar (Spark)
- VSlider
- VSlider (Spark)
- XML
- XMLList
- XMLListCollection
- ZipCodeValidator
- ZipCodeValidatorDomainType
- Zoom
-
Articles
- December 2010
- November 2010
- October 2010
- September 2010
- August 2010
- July 2010
- June 2010
- May 2010
- April 2010
- March 2010
- February 2010
- January 2010
- December 2009
- November 2009
- October 2009
- September 2009
- August 2009
- July 2009
- June 2009
- May 2009
- April 2009
- March 2009
- February 2009
- January 2009
- December 2008
- November 2008
- October 2008
- September 2008
- August 2008
- July 2008
- June 2008
- May 2008
- April 2008
- March 2008
- February 2008
- January 2008
- December 2007
- November 2007
- October 2007
- September 2007
- August 2007
- July 2007
-
Meta


Geert,
Thanks. Yeah, somewhere between WordPress and my current theme, the single backslashes need to get doubled up. I fixed the entry above.
Peter
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
Peter,
1) In actionscript it should read
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
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
Sorry, code was swollen by the blog parser
Elextra,
The
restrictrestrict property only accepts “simple” strings, not regular expressions, and it basically matches how the TextField class’srestrictproperty 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
changeand/ortextInputevents and then calling a custom RegExpValidator: http://livedocs.adobe.com/flex/3/langref/mx/validators/RegExpValidator.htmlPeter
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”
Steps to reproduce:
1. TextInput creates dynamically
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
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?
@Usman Ajmal,
Sure. But I’d probably just check that the
selectedIndexproperty isn’t -1, as seen in the following example: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. :)
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.
@Sameera Sandaruwan,
Try setting the
errorColorstyle; “Customizing a Flex TextInput control’s error color”.Peter