2

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?

4

2 回答 2

3

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 *
于 2013-10-29T16:28:31.987 回答
1

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 
于 2013-10-29T17:38:23.677 回答