0

I am trying to prevent non-numeric characters from ever showing in tel and numeric inputs with an angularjs directive.

<input type="tel" ... />
<input type="number" ... />

I found this almost perfect Stack Overflow answer, however it only works with text inputs. I need to use tel and number inputs so the correct keyboard appears on mobile devices.

How can this directive be made to work with tel AND number inputs?

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, '');
        if (val !== clean) {
          ngModelCtrl.$setViewValue(clean);
          ngModelCtrl.$render();
        }
        return clean;
      });

      element.bind('keypress', function(event) {
        if(event.keyCode === 32) {
          event.preventDefault();
        }
      });
    }
  };
});

Codepen using the almost-working directive can be found here.

4
  • You mean that you want to support "-" ect? I believe that "tel" only works in Safari btw. Commented Apr 16, 2015 at 3:07
  • i believe you can use pattern for excepting numerics only. Commented Apr 16, 2015 at 3:10
  • @njfife - I am developing a cross platform ionic cordova app that runs on iOS and Android. I switch to using the tel input on iOS and number input on Android. Commented Apr 16, 2015 at 14:48
  • @maddog - pattern does not prevent the undesired characters from being typed into the input. Commented Apr 16, 2015 at 14:52

1 Answer 1

0

"If ever there were a most underused input type this would be it. Tel offers the user a numeric keypad. If all you want from the user is a number you should be using the tel input type. Forget using number, because that actually includes a bunch of stuff which isn't numbers."

( from http://mobileinputtypes.com )

Did you try just changing the text type to type="tel"?

The directive continues to function on a computer and it displays the number keypad on mobile.

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.