Courtney Stephenson
Courtney Stephenson

Reputation: 930

Preventing the user from entering < or > into form field

I'm trying to prevent users from entering < or > into my form fields using JavaScript. Here's what I have so far:

$(document).on('keydown', function (e) {
    regex = new RegExp("\<|>");
    var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
    if (!regex.test(key)) {
        event.preventDefault();
        return false;
    }
});

It's still allowing those characters, how do I stop this?

Upvotes: 4

Views: 87

Answers (2)

Samsquanch
Samsquanch

Reputation: 9146

Two things worth noting:

  • keypress isn't fully supported for all keys across all browsers. You should use keydown or keyup
  • the < and > key code vary across OS' and keyboard layouts. Hard coding the keycodes won't consistently work

For a cross-OS and cross-keyboard-layout solution (although not as clean), you can do this:

$(document).on('keyup', 'input, textarea', function (e) {
    regex = new RegExp("\<|>");
    var val = $(this).val();
    $(this).val(val.replace(regex, ''));
});

This strips the < and > keys from the input on keyup. The user will see this happening, but it should always catch the desired keys and strip them.

Upvotes: 3

Digital Chris
Digital Chris

Reputation: 6202

Why bother translating then regexing? I like to keep it simple:

$(document).on('keypress', function (e) {
    if ((e.which == 62) || (e.which == 60)) { // greater than or less than key pressed
        e.preventDefault();
    }    
});

Edit to add:

Alternate if condition based on @Samsquanch feedback:

if ((String.fromCharCode(e.which) == '>') || (String.fromCharCode(e.which) == '<')) { // greater than or less than key pressed

Upvotes: 5

Related Questions