如何使用正则表达式验证 Javascript 中的数字字段?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15699094/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to validate a Number field in Javascript using Regular Expressions?
提问by Vaibhav Jhaveri
Is the following correct?
以下是否正确?
var z1=^[0-9]*\d$;
{
if(!z1.test(enrol))
{
alert('Please provide a valid Enrollment Number');
return false;
}
}
Its not currently working on my system.
它目前不适用于我的系统。
回答by techfoobar
You can test it as:
您可以将其测试为:
/^\d*$/.test(value)
Where:
在哪里:
- The
/
at both ends mark the start and end of the regex - The
^
and$
at the ends is to check the full string than for partial matches \d*
looks for multiple occurrences of number charcters
- 该
/
两端标记的正则表达式的开始和结束 - 最后的
^
and$
是检查完整字符串而不是部分匹配 \d*
查找多次出现的数字字符
You do not need to check for both \d
as well as [0-9]
as they both do the same - i.e. match numbers.
您不需要检查两者\d
,[0-9]
因为它们都做同样的事情 - 即匹配号码。
回答by Sergey Sahakyan
var numberRegex = /^\s*[+-]?(\d+|\.\d+|\d+\.\d+|\d+\.)(e[+-]?\d+)?\s*$/
var isNumber = function(s) {
return numberRegex.test(s);
};
"0" => true
"3." => true
".1" => true
" 0.1 " => true
" -90e3 " => true
"2e10" => true
" 6e-1" => true
"53.5e93" => true
"abc" => false
"1 a" => false
" 1e" => false
"e3" => false
" 99e2.5 " => false
" --6 " => false
"-+3" => false
"95a54e53" => false
回答by Kathir
You this one and it allows one dot and number can have "positive" and "negative" symbols
你这个,它允许一个点和数字可以有“正”和“负”符号
/^[+-]?(?=.)(?:\d+,)*\d*(?:\.\d+)?$/.test(value)
/^[+-]?(?=.)(?:\d+,)*\d*(?:\.\d+)?$/.test(value)
回答by Adam Plocher
Try:
尝试:
var z1 = /^[0-9]*$/;
if (!z1.test(enrol)) { }
Remember, *
is "0 or more", so it will allow for a blank value, too. If you want to require a number, change the *
to +
which means "1 or more"
请记住,*
是“0 或更多”,因此它也允许一个空白值。如果您想要求一个数字,请将 更改*
为+
表示“1 或更多”
回答by Jean
If you looking for something simple to test if a string is numeric, just valid numbers no +, - or dots.
如果您正在寻找一些简单的东西来测试字符串是否为数字,则只需有效数字,而不是 +、- 或点。
This works:
这有效:
/^\d*$/.test("2412341")
/^\d*$/.test("2412341")
true
真的
/^\d*$/.test("2412341")
/^\d*$/.test("2412341")
false
错误的