2

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");
 }
4
  • Is it possible for you to use an input number instead of an input field ? Could be way easier Commented Jul 6, 2015 at 9:54
  • I agree wit @Apédémak, it would be much easier to use an input number. If you really wanted to, however, you could loop over the string checking if it contains numbers 0-9. Commented Jul 6, 2015 at 9:56
  • Instead of code.val(numbers) try new RegExp(numbers).test(code) Commented Jul 6, 2015 at 9:59
  • Instead of checking you can restrict the user to give appropriate value. Check this low size plugin, which will help you solve the issue.. github.com/Jeevanandanj/angular-input-decimal-separator Commented Feb 22, 2016 at 10:39

4 Answers 4

3

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");
}
Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

thanks vaibhav but in my case the user should be able to enter values and i want to show an alert for the case if he has not entered numbers , nyways thanks for the answer but the requirement is lil bit different here
0

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

Comments

0

try this hope this is what you are looking for

 if(angular.isNumber(value))
       { 
        //your code here 
       }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.