Reputation: 270
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 .
var numbers =/^[0-9]+$/;
var code = $scope.Nuser.centerCode;
alert(code);
if(code.val(numbers))
{
alert(code.val(numbers));
}
else
{
alert("enter numbers only");
}
Upvotes: 2
Views: 16416
Reputation: 2671
I would suggest you to use ng-pattern instead . Something like following :
<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 :
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.
Upvotes: 2
Reputation: 749
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.
var numbers = new RegExp(/^[0-9]+$/);
var code = $scope.Nuser.centerCode;
if(numbers.test(code))
{
alert('code is numbers');
}
else
{
alert("enter numbers only");
}
Upvotes: 3
Reputation: 781
try this hope this is what you are looking for
if(angular.isNumber(value))
{
//your code here
}
Upvotes: 0
Reputation: 4808
You can simply convert string to number and test is it's NaN
(Not a Number)
isNaN(+$scope.Nuser.centerCode)
if it's false
it means your centerCode contain only numbers
Upvotes: 0