halapgos1
halapgos1

Reputation: 1195

AngularJS Input[type="number"] Validation allow only numbers to be entered

I have an input box asking for a number and what I'm trying to do is to make sure the user does not type any letter or any digit that is not valid.

This is my code so far:

    <form name="userForm" novalidate>
        Calories Needed : 
        <input type="number" min="0" ng-model="user.calories">
    </form>

I've been looking for a way using AngularJS but have had no luck. I've come across posts where they suggested creating a directive but I was looking for another technique. I'm still a beginner so I don't want to just use code w/o understanding what exactly is going on.

Upvotes: 0

Views: 5043

Answers (2)

Chris Lonardo
Chris Lonardo

Reputation: 141

You'll want to read up on Angular's form validation- tutorial

It's as simple as adding "required" to your input, and 'novalidate' to the form element:

<form name="testForm" novalidate>
       <input type="number" required name="numberinput" class="form-control" ng-model="someNumber">
</form>

plunker

Upvotes: 0

Mark Pieszak - Trilon.io
Mark Pieszak - Trilon.io

Reputation: 67181

You're in luck I have a directive I use myself everywhere for this instance.

It's as easy as slapping <input valid-number /> on an input. Voila!

angular.module('yourApp')
 .directive('validNumber', function () {
    return {
        require: '?ngModel',
        link: function (scope, element, attrs, ngModelCtrl) {
            // make sure we're connected to a model
            if (!ngModelCtrl) {
                return;
            }

            ngModelCtrl.$parsers.push(function (val) {
                // this is a test for whether it's undefined (from textbox)
                // or null when using type="number"
                if (val === undefined || val === null) {
                    val = '';
                }

                // here we try and clean it to make sure it's only numbers
                var clean = val.toString().replace(/[^0-9]+/g, '');

                // if a letter/etc got in there, set the model to the "cleaned" number value
                if (val !== clean) {
                    ngModelCtrl.$setViewValue(clean);
                    ngModelCtrl.$render();
                }
                return clean;
            });

            // this is to test for "32" = SPACEBAR
            // and "101" = e (Chrome for some reason let's E go through in type="number"
            element.bind('keypress', function (e) {
                var code = e.keyCode || e.which;

                // Remove code === 101 part if you want 'e' to go through
                if (code === 101 || code === 32) {
                    e.preventDefault();
                }
            });
        }
    };
});

Upvotes: 2

Related Questions