最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Regex not allowing negative numbers - Stack Overflow

programmeradmin5浏览0评论

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\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;  
 }

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\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;  
 }
Share Improve this question edited Jul 6, 2011 at 9:25 Sai Kalyan Kumar Akshinthala 11.8k8 gold badges45 silver badges68 bronze badges asked Jul 6, 2011 at 9:22 dazzledazzle 1151 gold badge2 silver badges6 bronze badges 2
  • My advice is to try to learn to do your job... someday they won't ask you to refactor someone's else code and you will have to write yours. – SJuan76 Commented Jul 6, 2011 at 9:27
  • yes, you are right..but I didnt understand what this part of the code did ...^[0-9]*\\.?[0-9]{0,2}$ – dazzle Commented Jul 6, 2011 at 9:32
Add a ment  | 

2 Answers 2

Reset to default 4

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)

  1. 暂无评论