Question

I have the following code in Titanium to check if user input is non-numeric:

textBox.addEventListener('change', function (e) {
    var patt = new RegExp('^\d+(\.\d{1,2})?$','gi');
    if (e.value.match(patt) != null) {
        //insert action here
    }
});

I personally would like to delete non-decimal characters when a user tries to input one. However, in order to do so, I would need to use replace(inversePatt, ""). I would like to know, how do I get the inverse of my regular expression?

Was it helpful?

Solution

to delete non-decimal characters, you should be able to match every:

[^\.\d]

group returned.

([^.\d] should work - here a dot needn't be escaped)

The carat inverts inside brackets. It basically means "not a dot or a number".

Check out:

http://www.scriptular.com

EDIT: I think this has your answer:

Restricting input to textbox: allowing only numbers and decimal point

EDIT 2: You could also use this:

var success = /^\d*\.?\d{0,2}$/.test(input);

as per:

Limiting input field to one decimal point and two decimal places

you can also demand a number before the decimal point like so:

var success = /^\d+\.?\d{0,2}$/.test(input); // uses + instead of *

OTHER TIPS

If you want to handle chars in a key event, something like below should work.
As an acceptance validation, use something like \d to make sure a digit is present.

 # ^(?:\.|\d*|\d+\.|\d*\.\d+)$
 # "^(?:\\.|\\d*|\\d+\\.|\\d*\\.\\d+)$"


 ^                       # BOL 
 (?:
      \.                 # dot, or 
   |  
      \d*                # optional digits (if no digits, matches ^$) 
   |  
      \d+ \.             # digits and dot
   |  
      \d* \. \d+         # optional digits and dot and digits
 )
 $                       # EOL 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top