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

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.