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.key
in 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;
}
});
}
};
});
source
share