Prevent typing letters into the angular input

Asked

Viewed 1,218 times

1

how to prevent letters being typed into a input where only angular numbers should be typed? Only with directives is it possible?

  • 1

    Related: https://answall.com/questions/173490/input-do-tipo-number-n%C3%A3o-considera-o-maxlength/173492

  • 3

    No use using the type=number?

  • 1

    doc so I found this https://docs.angularjs.org/aping/input/input%5Bnumber%5D

  • Why not use the "type" html property?

  • @LINQ If you also need to support browser versions that do not support the specification of type, or partially implement, yes.

  • So, @Onosendai. That’s why I asked before writing to you =D By the way, very good answer

  • @LINQ Why, Thank you Kind sir.

Show 2 more comments

1 answer

3

Use a directive that removes all non-numeric characters.

angular.module('myApp', [])
.directive('numerosApenas', function() {
  return {
    require: 'ngModel',
    link: function (scope, element, attr, ngModelCtrl) {
    
      function parserNumerico(textoOriginal) {
      
        // Troque tudo o que não for um dígito válido por uma string vazia
        var inputSemNumeros = textoOriginal.replace(/[^0-9]/g, ''); 
        if(inputSemNumeros !== textoOriginal) {
        
            // reverta o valor para a versão sem números.
            ngModelCtrl.$setViewValue(inputSemNumeros);
            ngModelCtrl.$render();
        }
        return Number(inputSemNumeros);
      }
      
      ngModelCtrl.$parsers.push(parserNumerico);
    }
  }; 
})

.controller('myController', function($scope){

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.js"></script>
<div ng-app="myApp">
  <div ng-controller='myController'>
    <input type='text' numeros-apenas ng-model='valor' />
  </div>
</div>

Source.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.