regex - Restrict TextField to act like a numeric stepper -


i making numeric stepper scratch, want text field only accept numbers in format: xx.x, x.x, x, or xx x number. example: acceptable numbers: 1 22 15.5 3.5

none acceptable numbers: 213 33.15 4332 1.65

maybe how: http://livedocs.adobe.com/flash/9.0/actionscriptlangrefv3/flash/text/textfield.html#restrict

this got far:

var tx:textfield = new textfield(); tx.restrict="0-9."; //maybe there regular expression string this? tx.type=textfieldtype.input; tx.border=true; 

you can copy past in flash , should work.

thank sirs.

very similar thedarklins answer, little more elegant. , renders _tf.restrict obsolete, still recommend using it.

_tf.addeventlistener(textevent.text_input, _ontextinput_validate); 

both of these event listeners here exact same function identically. 1 written in 1 line smaller code. other see what's going on line line.

private function _ontextinput_validate(__e:textevent):void {     if ( !/^\d{1,2}(?:\.(?:\d)?)?$/.test(textfield(__e.currenttarget).text.substring(0, textfield(__e.currenttarget).selectionbeginindex) + __e.text + textfield(__e.currenttarget).text.substring(textfield(__e.currenttarget).selectionendindex)) ) __e.preventdefault(); } 

for more broken down version of event listener

private function _ontextinput_validate(__e:textevent):void {     var __reg:regexp;     var __tf:textfield;     var __text:string;      // set textfield thats causing event.     __tf = textfield(__e.currenttarget);      // set regular expression.     __reg = new regexp("\\d{1,2}(?:\\.(?:\\d)?)?$");      // or depending on how write it.     __reg = /^\d{1,2}(?:\.(?:\d)?)?$/;      // set text before selection.     __text = __tf.text.substring(0, __tf.selectionbeginindex);     // set text entered.     __text += __e.text;     // set text after selection, since entered text replace selected text may entered     __text += __tf.text.substring(__tf.selectionendindex);      // if test fails, prevent default     if ( !__reg.test(__text) )     {         __e.preventdefault();     } } 

i have had allow xx. valid response otherwise need type 123 go space , type . 12.3. not nice. 12. technically valid.


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -