Pages

Monday, September 12, 2011

Remove and/or prevent inserting invalid characters on client side

This simple Javascript will prevent inserting ' < ' ' > ' and ' " ' characters from your HTML form,

<SCRIPT language=Javascript>
<!--
      function reminvalid(evt)
      {
         var charCode = (evt.which) ? evt.which : event.keyCode
         if ((charCode < 60 || charCode > 62) && charCode != 34)
            return true;

         return false;
      }

//-->
</SCRIPT>


The primary requirement of this code is to prevent cross site scripting on the web form. You can modify the char code(s) as the requirement. 

Unfortunately this won't prevent copy and paste insertion. So I had to embed this code too..

function delinvalid(string)
    {   
        output =  string.replace(/[<>"]+/g,' ');
        return output;
    }

This will remove the unwanted characters and replace by a space (or any other character you specify after the comma, in this case ' ')

You can use it this way too,


string.replace(/[^a-zA-Z 0-9]+/g,' ');

Then it will remove everything other than a-z A-Z 0-9 and space.

Remember to use the below notation if you want to replace the '^' sign.

string.replace(/\^/g, '\r\n');

Here is my input element,

<input name="***" type="text" size="**" id="**" onkeypress="return reminvalid(event)" onChange="this.value=delinvalid(this.value)">

Simple and powerful Javascripts....

Regards.

No comments:

Post a Comment