admin管理员组文章数量:1402485
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
2 Answers
Reset to default 4You 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).
本文标签: javascriptRegex not allowing negative numbersStack Overflow
版权声明:本文标题:javascript - Regex not allowing negative numbers - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744341095a2601480.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论