Home Directive for restricting typing by Regex in AngularJS

# Directive for restricting typing by Regex in AngularJS

Geison Santos
1#
Geison Santos Published in 2018-01-12 22:10:47Z
 I coded an angular directive for inhibiting typing from inputs by specifying a regex. In that directive I indicate a regex that will be used for allow the input data. Conceptually, it works fine, but there are two bugs in this solution: In the first Plunker example the input must allow only numbers or numbers followed by a dot [.], or numbers followed by a dot followed by numbers with no more than four digits. If I type a value '1.1111' and after that I go to the first digit and so type another digit (in order to get a value as '11.1111') , nothing happening. The bug is in the fact I use the expression elem.val() + event.key on my regex validator. I do not know how to get the whole current value for a input on a keypress event; The second one is the fact that some characters (grave, acute, tilde, circumflex) are being allowed on typing (press one of them more than once), althought the regex does not allow them. What changes do I need to make in my code in order to get an effective type restriction by regex? 

Restrict typing by RegExp

PATTERN 1 (^\d+$|^\d+[.]$|^\d+[.]\d{1,4}$) ONLY NUMBERS ONLY STRINGS  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; } }); } }; });  Mindaugas Bernatavičius 2# Mindaugas Bernatavičius Reply to 2018-01-12 23:04:57Z  You specified 4 different patterns 3 different pattens in your regex separated by an alteration sign: ^\d+$|^\d+[.]$|^\d+[.]\d{1,4}$ - this will not fulfill the criteria of input must allow only numbers followed by a dot [.], followed by a number with no more than four digits. The bug "where nothing happens" occurs because the variable you are checking against is not what you think it is, check the screenshot on how you can inspect it, and what it is: Can not reproduce.
Louis
3#
 If this were my code, I'd change tactics entirely: I would listen for input events instead of trying to micromanage the user interactions with the field. The approach you are taking, in general, has problems. The biggest one is that keypress won't be emitted for all changes to the field. Notably, It is not triggered by DELETE and BACKSPACE keys. Input methods can bypass it. When you entered diacritics as diacritics, your code was not registering the change. In general, if the user is using an input method, there is no guarantee that each new character added to the field will result in a keypress event. It depends on the method the user has chosen. keypress does not help when the user cuts from the field or pastes into the field. You could add code to try to handle all the cases above, but it would get complex quick. You've already run into an issue with elem.val() + event.key because the keypress may not always be about a character inserted at the end of the field. The user may have moved the caret so you have to keep track of caret position. One comment suggested listening to keyup but that does not help with input methods or paste/cut events. In contrast, the input event is generated when the value of the field changes, as the changes occur. All cases above are taken care of. This, for instance, would work: elem.bind('input', function(event) { var validator = new RegExp(regex); elem.css("background-color", !validator.test(elem.val()) ? "red" : null); });  This is a minimal illustration that you could plop into your fiddle to replace your current event handler. In a real application, I'd give the user a verbose error message rather than just change the color of the field and I'd create validator just once, outside the event handler, but this gives you the idea. (There's also a change event but you do no want to use that. For text fields, it is generated when the focus leaves the field, which is much too late.)
 See Plnkr Fixed as per your approach: The explanation of why and the changes are explained below. Side note: I would not implement it this way (use ngModel with $parsers and $formatters, e.g. https://stackoverflow.com/a/15090867/2103767) - implementing that is beyond the scope of your question. However I found a full implementation by regexValidate by Ben Lesh which will fit your problem domain:- If I type a value '1.1111' and after that I go to the first digit and so type another digit (in order to get a value as '11.1111') , nothing happening. because in your code below var input = elem.val() + event.key; you are assuming that the event.key is always appended at the end. So how to get the position of the correct position and validate the the reconstructed string ? You can use an undocumented event.target.selectionStart property. Note even though you are not selecting anything you will have this populated (IE 11 and other browsers). See Plnkr Fixed The second one is the fact that some characters (grave, acute, tilde, circumflex) are being allowed on typing (press one of them more than once), althought the regex does not allow them. Fixed the regex - correct one below: ^[0-9]*(?:\.[0-9]{0,4})?\$ So the whole thing looks as below  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(''); } } 
 You can change the event to keyup, so the test would run after every additional character is added. It means you need to save the last valid input, so if the user tries to insert a character that'll turn the string invalid, the test will restore the last valid value. Hence, the updated directive: 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; }); } }; });