Reputation: 41
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>
Upvotes: 2
Views: 15218
Reputation: 1824
Try with this...
var iChars = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?";
for (var i = 0; i < document.formname.fieldname.value.length; i++) {
if (iChars.indexOf(document.formname.fieldname.value.charAt(i)) != -1) {
alert ("Your username has special characters. \nThese are not allowed.\n Please remove them and try again.");
return false;
}
}
Upvotes: 1
Reputation: 26183
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.Upvotes: 1
Reputation: 4140
why not simply check the character pressed on "onKeyDown" event?
<textarea id="foo"></textarea>
<script>
document.getElementById('foo').onkeydown = validate;
function validate(){
var evtobj = window.event? event : e; // IE event or normal event
var unicode = evtobj.charCode? evtobj.charCode : evtobj.keyCode;
var actualkey = String.fromCharCode(unicode);
]
return (/^[A-zÑñ0-9]*$/i).test(actualKey);
</script>
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
Upvotes: 0