In this tutorial you will learn how to restrict the special characters being entered in textbox. Sometimes you want to restrict some special characters being entered in textbox of form to prevent the sql injection that can harm your database very badly. So Let's have a look over how to do so.
How to restrict special characters being entered in textbox using javascript?
<script language="javascript" type="text/javascript"> function check(e) { var keynum var keychar var numcheck // For Internet Explorer if (window.event) { keynum = e.keyCode } // For Netscape/Firefox/Opera else if (e.which) { keynum = e.which } keychar = String.fromCharCode(keynum) //List of special characters you want to restrict if (keychar == "'" || keychar == "`") { return false; } else { return true; } } </script>
Now let's have a look over how to call this special characters restriction function in a textbox.
For aspx server side textbox control
<asp:TextBox ID="txtName" runat="server" onkeypress="return check(event)" ></asp:TextBox>
For html textbox control
<input type="text" name="txtName" id="txtName" onkeypress="return check(event)">
You can restrict any other character or number other than special characters too, just by simply add it in the list of characters to be restricted such as for example I want to restrict the character a too then the code will be
if (keychar == "'" || keychar == "`" || keychar == "a")
So this is the way to handle and restrict the special characters being entered in textbox using javascript.
Keep Coding…
8 comments:
This is very good.
Thanks
This is very good.
Thanks
Nice.
The same tutorial is here aswell
http://photonservers.org/index.php?topic=8.msg8;topicseen#msg8
It took me half hour at least to write this tutorial but i think Rajan Solanki takes 1 min to copy tutorial from other websites and paste it into http://photonservers.org. Anyways Cheerz....
The code is good, but the author's statements that this would prevent SQL injection are incorrect. Client-side technologies (IE, javascript) can't be used to do this.
My Dear Sir, this tutorial covers the beginners’ level to prevent SQL injection. I always recommend to write both client side and server side code to prevent the SQL injections because incase javascript is disabled and there is no code written in server side to tackle the sql injections then it will damage your database badly. I also prefer to use asp.net validation controls, if you are using asp.net as a programming language, those controls are very handy. They will tackle sql injections attack at client side if javascript is enabled and if javascript is disabled then they will tackle sql injections at server side automatically.
Thank u :)
Hey
thanks
a lot
cleared my doubt
Post a Comment