akzhan / jquery-keyfilter

This plugin filters keyboard input by specified regular expression.
http://akzhan.github.com/jquery-keyfilter/
37 stars 11 forks source link

Modern Version of this component #17

Open melloware opened 1 year ago

melloware commented 1 year ago

Now that it is 2023 and ALL browsers support event.key here is a modern slim version of this plugin that works in all browsers both mobile and desktop...

/*
 * This plugin filters keyboard input by specified regular expression.
 * Version 1.9
 *
 * Source code inspired by Ext.JS (Ext.form.TextField, Ext.EventManager)
 *
 * Procedural style:
 * $('#ggg').keyfilter(/[\dA-F]/);
 * Also you can pass test function instead of regexp. Its arguments:
 * this - HTML DOM Element (event target).
 * c - String that contains incoming character.
 * $('#ggg').keyfilter(function(c) { return c != 'a'; });
 *
 * Class style:
 * <input type="text" class="mask-num" />
 *
 * Available classes:
 * mask-pint:     /[\d]/
 * mask-int:      /[\d\-]/
 * mask-pnum:     /[\d\.]/
 * mask-money     /[\d\.\s,]/
 * mask-num:      /[\d\-\.]/
 * mask-hex:      /[0-9a-f]/i
 * mask-email:    /[a-z0-9_\.\-@]/i
 * mask-alpha:    /[a-z_]/i
 * mask-alphanum: /[a-z0-9_]/i
 */
(function($) {
    var defaultMasks = {
        pint: /[\d]/,
        'int': /[\d\-]/,
        pnum: /[\d\.]/,
        money: /[\d\.\s,]/,
        num: /[\d\-\.]/,
        hex: /[0-9a-f]/i,
        email: /[a-z0-9_\.\-@]/i,
        alpha: /[a-z_]/i,
        alphanum: /[a-z0-9_]/i
    };

    $.fn.keyfilter = function(re) {
        return this.on('keypress.keyfilter', function(e) {
            var key = e.key;
            var isPrintableKey = key.length === 1 || key === 'Unidentified';
            if (!isPrintableKey) {
                return;
            }

            var ok = true;
            if (typeof re === "function") {
                ok = re.call(this, key);
            } else {
                ok = re.test(key);
            }
            if (!ok) {
                e.preventDefault();
            }
        });
    };

    $.extend($.fn.keyfilter, {
        defaults: {
            masks: defaultMasks
        },
        version: 1.9
    });

    $(document).ready(function() {
        var tags = $('input[class*=mask],textarea[class*=mask]');
        for (var key in $.fn.keyfilter.defaults.masks) {
            tags.filter('.mask-' + key).keyfilter($.fn.keyfilter.defaults.masks[key]);
        }
    });

})(jQuery);