javascript 如何检查输入值只有角度数字?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31242701/
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 check input value has only numbers in angular?
提问by Anky
I want to compare a value of a field centerCode which is entered by a user into an input field. Then I want to check if it is a number and show the appropriate alert accordingly. I am not able to compare the value or variable number with the variable code .
我想比较用户在输入字段中输入的字段 centerCode 的值。然后我想检查它是否是一个数字并相应地显示适当的警报。我无法将值或变量编号与变量代码进行比较。
var numbers =/^[0-9]+$/;
var code = $scope.Nuser.centerCode;
alert(code);
if(code.val(numbers))
{
alert(code.val(numbers));
}
else
{
alert("enter numbers only");
}
回答by Jonathon Blok
You're along the right lines. Numbers needs to be a Regex though, and you need to use the test
function to check the input against it. The test
function will return true if the string is all numbers, or false if there is anything else in it.
你是对的。数字需要是一个正则表达式,你需要使用该test
函数来检查它的输入。该test
字符串是否是所有的数字,还是假的,如果有任何东西在里面函数将返回true。
var numbers = new RegExp(/^[0-9]+$/);
var code = $scope.Nuser.centerCode;
if(numbers.test(code))
{
alert('code is numbers');
}
else
{
alert("enter numbers only");
}
回答by Vaibhav Pachauri
I would suggest you to use ng-pattern instead . Something like following :
我建议你改用 ng-pattern 。类似于以下内容:
<input type="text" ng-pattern="/^[0-9]{1,7}$/" ng-model="inputNumber"/>
It will only allow the user to enter the number.
它只允许用户输入号码。
You can use angular.isNumber
to check if the entered value is a number or not. Try something like the following :
您可以使用angular.isNumber
检查输入的值是否为数字。尝试类似以下内容:
if(angular.isNumber($scope.Nuser.centerCode)){
alert('Center Code is a number');
}else {
alert('Center Code is not a number');
}
Hope this will do the trick.
希望这能解决问题。
回答by Shoaib Ahmed
try this hope this is what you are looking for
试试这个希望这就是你要找的
if(angular.isNumber(value))
{
//your code here
}
回答by Khalid
You can simply convert string to number and test is it's NaN
(Not a Number)
您可以简单地将字符串转换为数字并测试它是NaN
(不是数字)
isNaN(+$scope.Nuser.centerCode)
if it's false
it means your centerCode contain only numbers
如果是,false
则意味着您的 centerCode 仅包含数字