Directive to restrict typing with Regex in AngularJS

I encoded the angular directive to prohibit input by specifying a regular expression. In this directive, I specify the regular expression that will be used to input the input. It is clear that it works fine, but there are two errors in this solution:

  • In the first Plunker, the input example should contain only numbers or , followed by a period [.] Or , followed by a period, followed by numbers containing no more than four digits .
    • If I dial the value "1.1111", and after that I go to the first digit and therefore dial another digit (to get the value "11.1111"), nothing happens. The error is that I use an expression elem.val() + event.keyin my regex validator. I do not know how to get all the current value for input in a keypress event;
  • Secondly, the fact that some characters (serious, sharp, tilde, envelope) are allowed when typing (press one of them more than once), although the regular expression does not allow them.

What changes do I need to make in my code in order to get an efficient type restriction using regular expression?

  <html ng-app="app">    
  <head>
    <script data-require="angularjs@1.6.4" data-semver="1.6.4" src="https://code.angularjs.org/1.6.4/angular.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>
    <h1>Restrict typing by RegExp</h1>
    PATTERN 1 (^\d+$|^\d+[.]$|^\d+[.]\d{1,4}$) <input type="text" allow-typing="^\d+$|^\d+[.]$|^\d+[.]\d{1,4}$"/><br>
    ONLY NUMBERS <input type="text" allow-typing="^[0-9]+$"/><br>
    ONLY STRINGS <input type="text" allow-typing="^[a-zA-Z]+$"/>
  </body>

</html>

Directive

angular.module('app', []).directive('allowTyping', function() {
  return {
    restrict: 'A',
    link: function(scope, elem, attrs, ctrl) {
      var regex = attrs.allowTyping;
      elem.bind('keypress', function(event) {
        var input = elem.val() + event.key;
        var validator = new RegExp(regex);
        if(!validator.test(input)) {
          event.preventDefault();
          return false;
        }
      });
    }
  };
});
+4
source share
4 answers

. Plnkr :

. : ( ngModel $parsers $formatters, fooobar.com/questions/27198/...) - , . regexValidate by Ben Lesh, : -

"1.1111", , ( "11.1111" ), .

var input = elem.val() + event.key;

, event.key .

, ? event.target.selectionStart. , , (IE 11 ). . Plnkr

-, , (, , , ) ( ), .

- :

^[0-9]*(?:\.[0-9]{0,4})?$

,

  link: function(scope, elem, attrs, ctrl) {
    var regex = attrs.allowTyping;
    elem.bind('keypress', function(event) {
      var pos = event.target.selectionStart;
      var oldViewValue = elem.val();
      var input = newViewValue(oldViewValue, pos, event.key);
      console.log(input);
      var validator = new RegExp(regex);
      if (!validator.test(input)) {
        event.preventDefault();
        return false;
      }
    });

    function newViewValue(oldViewValue, pos, key) {
      if (!oldViewValue) return key;
      return [oldViewValue.slice(0, pos), key, oldViewValue.slice(pos)].join('');
    }
  }
0

, : input , .

, , , . : keypress . ,

, , . elem.val() + event.key, keypress , . , , . keyup, / .

, input . . , , :

elem.bind('input', function(event) {
  var validator = new RegExp(regex);
  elem.css("background-color", !validator.test(elem.val()) ? "red" : null);
});

, , . , , validator , , .

( change, . , , .)

+1
  • 4 3 pattens , : ^\d+$|^\d+[.]$|^\d+[.]\d{1,4}$ - input must allow only numbers followed by a dot [.], followed by a number with no more than four digits. , , , , , , , , , :

enter image description here

  1. .
0

keyup, .

, , , , , .

, :

angular.module('app', [])
    .directive('allowTyping', function()  {
        return {
            restrict : 'A',
            link : function(scope, elem, attrs, ctrl) {
                var regex = attrs.allowTyping;
                var lastInputValue = "";
                elem.bind('keyup', function(event) {
                var input = elem.val();
                var validator = new RegExp(regex);

                if (!validator.test(input))
                    // Restore last valid input
                    elem.val(lastInputValue).trigger('input');
                else
                    // Update last valid input
                    lastInputValue = input;
                });
            }
        };
    });
0
source

Source: https://habr.com/ru/post/1692120/


All Articles