Prevent user input <or> in the form field

I am trying to prevent users from entering <or> in my form fields using JavaScript. Here is what I still have:

$(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;
    }
});

He still allows these symbols, how can I stop this?

+4
source share
2 answers

Why worry about translation, then regex? 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:

Alternatively, if the condition is based on @Samsquanch feedback:

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

Two things to note:

  • keypress is not fully supported for all keys in all browsers. You must use keydown or keyup
  • < > key code .

-OS - ( ) :

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

< > . , , .

+3

Source: https://habr.com/ru/post/1523357/


All Articles