Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to take inputs as only digits using Angular JS

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 395
    Comment on it

    Hello Reader! If you are designing a html form and wants to make it validate for accepting only digits as input then you can see the code below for the same:-

    You can create the html form like this way:-

    Validate Price

          <input type="text" ng-model="salary" valid-number />
      </div>
    </div>
    

    And to validate this form the JS file will go like this:-

    var app = angular.module('myApp', []);
    
        app.controller('MainCtrl', function($scope) {
        });
    
        app.directive('validNumber', function() {
          return {
            require: '?ngModel',
            link: function(scope, element, attrs, ngModelCtrl) {
              if(!ngModelCtrl) {
                return; 
              }
    
              ngModelCtrl.$parsers.push(function(val) {
                if (angular.isUndefined(val)) {
                    var val = '';
                }
                var clean = val.replace(/[^0-9\.]/g, '');
                var decimalCheck = clean.split('.');
    
                if(!angular.isUndefined(decimalCheck[1])) {
                    decimalCheck[1] = decimalCheck[1].slice(0,2);
                    clean =decimalCheck[0] + '.' + decimalCheck[1];
                }
    
                if (val !== clean) {
                  ngModelCtrl.$setViewValue(clean);
                  ngModelCtrl.$render();
                }
                return clean;
              });
    
              element.bind('keypress', function(event) {
                if(event.keyCode === 32) {
                  event.preventDefault();
                }
              });
            }
          };
        });
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: