Coder Social home page Coder Social logo

jquery-keyfilter's Introduction

Introduction

This jQuery plugin filters keyboard input by specified regular expression.

Source code inspired by Ext.JS (Ext.form.TextField, Ext.EventManager), but was modified to provide more accurate logic.

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'; });

CSS class attribute style

<input type="text" class="mask-num" />

Inputs with CSS classes like this will automatically have the corresponding regexp below applied.

Predefined classes with its regexps

  • mask-pint: /[\d]/
  • mask-int: /[\d\-]/
  • mask-pnum: /[\d\.]/
  • 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

Using different classes

You can apply these standard regexps to different classes if you wish.

$("input.integer").keyfilter($.fn.keyfilter.defaults.masks.int)

Extensibility

Keyfilter supports extending and changing of list of provided masks.

Example of extending

/*
 * Key filter masks for hosting.
 */

(function($)
{
  var hostingMasks = {
    dir: /[a-z0-9_\/\-\.]/i,
    ftpuser: /[a-z0-9_]/
  };

  $.extend($.fn.keyfilter.defaults.masks, hostingMasks);

})(jQuery);

Override built-in masks to allow french accents

/*
 * Key filter masks supporting french accents.
 */

(function($)
{
  $.extend($.fn.keyfilter.defaults.masks, {
    alpha:    /[a-zéèçàêoe_]/i,
    alphanum: /[a-zéèçàêoe0-9_]/i
  });
})(jQuery);

Overriding

You can fully override masks by simple assignment after the plugin loads but before the document.ready event fires.

$.fn.keyfilter.defaults.masks = { ... };

jquery-keyfilter's People

Contributors

akzhan avatar euberb avatar jiangti avatar seanadkinson avatar shankarcabus avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jquery-keyfilter's Issues

Best way to access default regexes?

Not an issue; just a question, maybe leading to a documentation patch.

Your default regexes meet my immediate needs, but I want to use different classes with them.

For instance, I don't want to use class="mask-num" because I'm also using a jquery plugin called 'MaskedInput', so this class name might create confusion on my team.

Instead, I'm doing this:

$('input.integer').keyfilter($.fn.keyfilter.defaults.masks.int)

My question is: is $.fn.keyfilter.defaults.masks.int the best way to access the default regexes?

Bower

What about add your plugin to Bower ?

Firefox: mask-int not blocking all characters

See: primefaces/primefaces#5110

Using Firefox with the following input

 <input type="text" class="mask-int" />

Hold <shift> and hack down keys 0 to 9, some (not all) of which will add their punctuation to the inputs below.

The issue is because you swithced to JQuery on("keypress") it automatically filters out non-printable characters: https://api.jquery.com/keypress/

This is similar to the keydown event, except that modifier and non-printing keys such as Shift, Esc, and delete trigger keydown events but not keypress events. Other differences between the two events may arise depending on platform and browser.

I have fixed it by removing this code as its no longer needed.

if($.browser.mozilla && (isNavKeyPress(e) || k == Keys.BACKSPACE || (k == Keys.DELETE && e.charCode == 0)))
{
return;
}

You can also remove this code as its no longer being used as well:

var isNavKeyPress = function(e)
{
var k = e.keyCode;
k = $.browser.safari ? (SafariKeys[k] || k) : k;
return (k >= 33 && k <= 40) || k == Keys.RETURN || k == Keys.TAB || k == Keys.ESC;
};

$.browser

This was deprecated in jQuery 1.3.

It was removed in jQuery 1.9.

Turkish keyboard problem

Hi,

We have a problem with the plugin in Turkish keyboards. Some of the special characters (e.g. #, $, @, ...) can be used even if they are filtered out in the component with a valid regex. Those characters that I mentioned are generated with an AltGr key in a Turkish layout keyboard. Some of the mappings include:

AltGr + 3 => #
AltGr + 4 => $
AltGr + Q => @
AltGr + ] => ~

For example with below definition, users can enter #, $, @ characters with the mentioned keystrokes.

<pe:keyFilter for="vkn" regEx="/[0-9]/i" preventPaste="false" />

You can look at the Turkish keyboard layout from http://ascii-table.com/keyboard.php/179

At the below line, e.ctrlKey and e.altKey are both true for the specified key strokes. I don't think it is the right fix, but if I remove the if condition from the script, it works like a charm.

https://github.com/akzhan/jquery-keyfilter/blob/master/jquery.keyfilter.js#L134

Thanks

FF Issue

Just to let you know the delete button doesn't work in FF

Making keypress event be live

Some elements are loaded by ajax, so is necessary making keypress event be live to catch and apply the filter to new elements.

include in keypress subcribtion function with source element parameter.

Hi,
I have a lot of elements with chstom attributes, i subscribe keypress in one function, but i don't know which control fires this event, it would be nice ti send also source control:

        if ($.isFunction(re))
        {
            ok = re.call(this, cc, add control or even e there);
        }
        else
        {
            ok = re.test(cc);
        }

Modern Version of this component

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);

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.