开发者

Regex not allowing negative numbers

I have a function which prevent users from entering negative values. Can anyone tell me what changes need to be made in the below regex to make this work.

function testAmount(obj){

var reg0Str = '^[0-9]*\\.?[0-9]{0,2}$';
var reg1Str =  /(^\d{1,3}(,\d开发者_StackOverflow\d\d)*$)/;
var temp = obj.value;

var reg0 = new RegExp(reg0Str);
var testFlag = reg0.test(remCommas(temp));
var testFlag0 = reg1Str.test(temp);
if(!(testFlag||testFlag0)){
      alert("Please enter a valid Number");
    obj.focus;
}
  return testFlag;  
 }


You allow digits characters only (and dot). Add \\-? on the beginning of your regex.


I didnt understand what this part of the code did ...^[0-9]*\.?[0-9]{0,2}$

^ anchors the regex to the start of the string (instead of matching anywhere in the string)
[0-9] is digits only, can be abbreviated as \d (or \d inside slashes)
* means to match 0 or more times
\\.? means an optional dot
[0-9]{0,2} means 0 to 2 digits
$ anchors the regex to the end of the string (nothing after the match)

So that's exactly zero or more digits followed by an optional dot followed by at most two digits. Note that the empty string is matched as well...

As for your request, Maras' answer is the right one.

I question the quality of the code you show, but that's another matter (why one string vs. a true regex, [0-9] vs. \d, etc. Looks like updates by different persons).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜