Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modern Version of this component #17

Open
melloware opened this issue Jan 21, 2023 · 0 comments
Open

Modern Version of this component #17

melloware opened this issue Jan 21, 2023 · 0 comments

Comments

@melloware
Copy link

melloware commented Jan 21, 2023

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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant