Hey guys, I'm thinking of ways to disable users from typing some special characters like < and >. But I would like them to use full stops and commas and question marks and exclamation marks and quotes. I've come up with this piece of code but it doesn't seem to allow any special character.:
<script type="text/JavaScript">
function valid(f) {
!(/^[A-zÑñ0-9]*$/i).test(f.value)?f.value = f.value.replace(/[^A-zÑñ0-9]/ig,''):null;
}
</script>
Try with this...
There are several ways of doing this, none of them are a good way to go tho, but we'll get to that.
you can bind to
onkeyup/onkeydown/onkeypress
events on the element and cancel events for characters you have blacklisted. This will not stop people from pasting the characters into the field however.You can bind to the
onchange
event of the element and them remove the blacklisted characters from it, once the user is done inputting.The problem with any type of sanitizing like this in javascript is that it is trivial for a user with a tiny bit of knowhow, to circumvent these measures and still upload the offending characters to the server anyway.
So if you don't want to allow special characters in the user generated input you should either
>
and<
for>
and<
for instance before outputting them anywhere on your webpage.why not simply check the character pressed on "onKeyDown" event?
This simply gets the key which was pressed, and if it is a valid one returns true, otherwise false, this, in term, determines if the key is actually written in the textarea or not