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?
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
Two things worth noting:
<
and >
key code vary across OS' and keyboard layouts. Hard coding the keycodes won't consistently workFor 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With