Kyle V. Kyle V. - 5 months ago 14
AngularJS Question

Restricting Characters in Input Field to a Set of Characters

Question Update: How can I prevent all characters except for the ones specified in a char array from being typed into an input field using AngularJS (or jQuery)?




Old Question:



I have a simple
<input type="text" />
field in my AngularJS application and I want the user to only be able to enter the following characters into the field:

0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ !\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~


I know that I can add
ng-pattern="allowed"
to the
<input>
and then set
$scope.allowed
to some regex pattern and that will mark the input invalid if any invalid characters are entered, but I also want to prevent restricted characters from being input into the field AT ALL.

So my question is composed of two questions:


  1. What regex pattern do I use to restrict the character set to the one I posted above?

  2. How do I prevent illegal characters from being entered in the field? (e.g. if you type a lowercase letter then it won't appear in the field to begin with, similarly if you try to paste in text containing any illegal characters they will be removed immediately)


Answer

To 'restrict some characters from being typed in' what comes in my mind is to attach event handlers for 'keyup', 'change', 'paste' events on inputs and when they are triggered to 'clean' their values against your pattern. I implemented the logic as jQuery plugin but you can adapt it to angular, use better naming or whatever you want.

The plugin:

$.fn.restrictInputs = function(restrictPattern){
    var targets = $(this);

    // The characters inside this pattern are accepted
    // and everything else will be 'cleaned'
    // For example 'ABCdEfGhI5' become 'ABCEGI5'
    var pattern = restrictPattern || 
        /[^0-9A-Z !\\"#$%&'()*+,\-.\/:;<=>?@\[\]^_`{|}~]*/g; // default pattern

    var restrictHandler = function(){
        var val = $(this).val();
        var newVal = val.replace(pattern, '');

        // This condition is to prevent selection and keyboard navigation issues
        if (val !== newVal) {
            $(this).val(newVal);
        }
    };

    targets.on('keyup', restrictHandler);
    targets.on('paste', restrictHandler);
    targets.on('change', restrictHandler);
};

Usage:

$('input').restrictInputs();

// Or ...

$('.my-special-inputs-decorated-with-this-class').restrictInputs();

Here is a JsFiddle Demo

Note: you can try to change the implementation to accept string with forbidden characters instead of regular expression and create the regex dynamically. Also you may find others events which are appropriate for triggering the 'cleaning'.