Reputation: 930
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
Reputation: 9146
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.
Upvotes: 3
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