Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 341
Courtney Stephenson Avatar asked Feb 15 '23 00:02

Courtney Stephenson


2 Answers

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
like image 86
Digital Chris Avatar answered Feb 24 '23 14:02

Digital Chris


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.

like image 32
Samsquanch Avatar answered Feb 24 '23 13:02

Samsquanch