Skip to content Skip to sidebar Skip to footer

Jquery: Filter Input On Keypress

I have a text field, which will accept only the following characters: Allowed characters: [a-z 0-9 + # - .] This is the same filter SO does in the 'Tags' field, when you're asking

Solution 1:

This worked for me:

$(function(){
    $('#t').keypress(function(e){
        var txt = String.fromCharCode(e.which);
        console.log(txt + ' : ' + e.which);
        if(!txt.match(/[A-Za-z0-9+#.]/)) 
        {
            returnfalse;
        }
    });
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputid="t" />

Solution 2:

/[^A-Za-z0-9+#-\.]/

This negates the match of any one of those characters. To make it match more than one character, you have to use a + in there:

/[^A-Za-z0-9+#-\.]+/
                  ^

And now to match the whole string, you need to add anchors:

/^[^A-Za-z0-9+#-\.]+$/
 ^                  ^

EDIT: Okay, it seems that the - here is also creating a range from character # to .. In this case, you can either escape it, or put it at the end:

/^[^A-Za-z0-9+#\-\.]+$/

/^[^A-Za-z0-9+#\.-]+$/

Solution 3:

You don't need to replace the char, only prevent it.

varchar = String.fromCharCode(event.which)
if (!char.match(/^[^A-Za-z0-9+#\.\-]+$/)) event.preventDefault();

Solution 4:

Alternate Solution

One thing that might help would be to use the .which field instead. Then simply return false when it doesn't fit. I actually have a huge object full of .which info for all major browsers. It includes arrays you could borrow from it to create something like:

var alphaNumericNcontrols = [ 8,9,13,16,17,18,19,20,32,33,34,35,36,37,38,39,40,44,45,46,145,48,49,50,51,52,53,54,55,56,57,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,96,97,98,99,100,101,102,103,104,105 ],
    illegal = {
        reg: [ 106,111,191,220 ],
        shift: [ 56,59,188,190,191,220,222 ]
    }

$(document).on("keydown", "input[type=text]", function(e) {
    var eKey = e.which || e.keyCode;
    if (alphaNumericNcontrols.indexOf(eKey) === -1) returnfalse;
    if (illegal.reg.indexOf(eKey) > -1) returnfalse;
    if (e.shiftKey && illegal.shift.indexOf(eKey) > -1) returnfalse;
});

See Working Example Here

Keep in mind my Object is not perfect and there are some updates I probably need to make to it, but i did my best to establish everything from every possible major browser!

Solution 5:

Thanks everyone.

Actually my problem was a little more difficult: filter invalid keys and start a ajax call for valid ones, in 2 different ways: if the user press SPACE/COMMA or while he/her still typing. Here's the code:

$(document).ready(function(){

$('#post_tags').keypress(function(e){
    var txt = String.fromCharCode(e.which);
    console.log(txt + ' : ' + e.which);

    if(txt.match(/^[^A-Za-z0-9+#\-\.]+$/))
    {
          returnfalse;
    }
})

$('#post_tags').keyup(function(event){
      code = event.whichvar token = String.fromCharCode(code)
      var txt = $(this).val()

              //create a new tag, take it out of textfieldif (code == 32 || code == 188)
      {
        console.log("AJAX new word keyup")

          $.ajax({
            type: 'get',
            url: '/posts/tags_change',
            dataType: "json",
            data: "query=" + $(this).val(),

            success: function(data) {
            console.log(data)
            $('#post_tags').val('')
            },

            error: function(data) {
                alert("Ajax error")
            }
          });
    }
    else
    {
                    //do autocomplete ajaxconsole.log("typing:" + txt)
    }

});

})

Dont' know if this is 100% right!

Post a Comment for "Jquery: Filter Input On Keypress"