2

I am using angularJS, and I'm trying to get an error to pop up if the input value is not a number.

Number Value: <input type="number" ng-model="mydata.number" ng-change="checkNumber()" />
            <p style="color:red" ng-show="numberError">
                {{ numberError }}
            </p>

And then inside $scope.checkNumber I check to see if it's NaN:

if(!$scope.mydata.number || isNaN($scope.mydata.number)) {
                $scope.numberError = "This must be a number";
            }

It appears that when I initially enter a string such as "fff" no error popups up, and we don't enter the checkNumber function, but if I enter "1fff" then it does enter the function and the error shows like it should.

If the input type is number and the initial character is not a number, does the ng-model not change?

1
  • 1
    ng-change on input type="number" only fires when a number is input so your code wont work this way Commented Oct 10, 2014 at 18:14

1 Answer 1

1

What about using the Angular built-in validation, like this:

<form name="myForm">
    Number Value: 
    <input type="number" ng-model="mydata.number" name="myNumber" />
    <p style="color:red" ng-show="myForm.myNumber.$dirty && !myForm.myNumber.$valid">
      {{ numberError }}
    </p>
</form>
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.