angularjs validate input and prevent change if invalid

前端 未结 4 1716
野性不改
野性不改 2021-01-06 11:15

I neeed an input field where I can enter only the values 1,2 or 3 so i\'m trying to build a directive which prevents all changes to the model if it doesn\'t match these valu

4条回答
  •  盖世英雄少女心
    2021-01-06 11:49

    You could always listen to the keypress event and prevent the character from making it through. Here is a plunker

    var app = angular.module('plunker', []);
    
    app.controller('MainCtrl', function($scope) {
      $scope.name = 'World';
      $scope.validValues = ['a','1','2'];
    });
    
    app.directive('myValidator', function ($parse) {
        return {
            scope: {
              validValues: '=validValues'
            },
            link: function (scope, elm, attrs) {
              elm.bind('keypress', function(e){
                var char = String.fromCharCode(e.which||e.charCode||e.keyCode), matches = [];
                angular.forEach(scope.validValues, function(value, key){
                  if(char === value) matches.push(char);
                }, matches);
                if(matches.length == 0){
                  e.preventDefault();
                  return false;
                }
              });
            }
        }   
    });
    

提交回复
热议问题