javascript JS:数字和空格的正则表达式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13229968/
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
JS: regex for numbers and spaces?
提问by matt
I'm using happyJSand use the regex underneath for phone validation
我正在使用happyJS并使用下面的正则表达式进行电话验证
phone: function (val) {
return /^(?:[0-9]+$)/.test(val);
}
However this ONLY allows numbers. I want the user to be able to enter spaces as well like
但是,这仅允许数字。我希望用户也能够输入空格
238 238 45383
Any idea why return /^(?:[0-9 ]+$)/.test(val);
is not doing the trick?
知道为什么return /^(?:[0-9 ]+$)/.test(val);
不这样做吗?
采纳答案by nhahtdh
This is my suggested solution:
这是我建议的解决方案:
/^(?=.*\d)[\d ]+$/.test(val)
The (?=.*\d)
asserts that there is at least one digit in the input. Otherwise, an input with only blank spaces can match.
该(?=.*\d)
断言有在输入的至少一个数字。否则,只有空格的输入才能匹配。
Note that this doesn't put any constraint on the number of digits (only makes sure there are at least 1 digit), or where the space should appear in the input.
请注意,这不会对位数(仅确保至少有 1 位数)或空格应出现在输入中的位置施加任何限制。
回答by Bruno
Try
尝试
phone: function (val) {
return /^(\s*[0-9]+\s*)+$/.test(val);
}
At least one number must be present for the above to succeed but please have a look at the regex example here
回答by Kamil Kie?czewski
Try
尝试
/^[\d ]*$/.test("238 238 45383")
console.log(/^[\d ]*$/.test("238 238 45383"));
回答by amit pandya
You can try the below regex for checking numbers and spaces.
您可以尝试使用以下正则表达式来检查数字和空格。
function isTextAndNumberSpaceOnly(text) {
var regex = /^[0-9 ]+$/;
if (regex.test(text)) {
return true;
} else {
return false;
}
}
回答by ahmad jaberi
Personally I use this code and it works properly:
我个人使用此代码并且它可以正常工作:
function validateMobile(mob)
{
var re = /^09[0-9]{9}$/
if(mob.match(re))
return true;
else
return false;
}