Tuesday, April 12, 2011

Restrict special characters from being entered into the textbox using Javascript

If the input from the textbox is going to be used as a filter criteria to retrieve records from the database, your application will throw exceptions as sql does not like special characters like '%', ', " in 'Where' and 'Like' clauses. You could write some javascript to restrict users from entering these special characters

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 == "`" || keychar == "%" || keychar == "\"" {
return false;
}
else {
return true;
}
}

Here is the asp.net tag

<asp:TextBox ID="txtName" runat="server" onkeypress="return check(event)"></asp:TextBox>

No comments: