Disabling some special characters in text area

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;



There are several ways of doing this, none of them are a good way to go tho, but we'll get to that.

  1. 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.

  2. 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

  1. remove them serverside after the userinput has been submitted
  2. keep them but encode them into html entities &gt; and &lt; for > and < for instance before outputting them anywhere on your webpage.

Try with this...

var iChars = "[email protected]#$%^&*()+=-[]\\\';,./{}|\":<>?";

  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;

why not simply check the character pressed on "onKeyDown" event?

<textarea id="foo"></textarea>

 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);

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


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.