Introduction
To enter validation in textbox, we can use JavaScript code. In ASP.NET, if we want to include validation in the textbox defined in aspx page, first create a JavaScript page. To create a JavaScript page, select "Add New Item" from "Website" menu. Then select "Jscript File". Write the below code in your "Jscript.js" file.
Using the Code
function chkChars(type,SChars)
{
if(SChars.indexOf(String.fromCharCode(window.event.keyCode))>=0)
{
return true;
}
if (window.event.keyCode==32) {
return true;
}
if (window.event.keyCode==13) {
return true;
}
switch(type)
{
case 'A': {
if ((window.event.keyCode<65 || window.event.keyCode>122) &&
(window.event.keyCode<90 || window.event.keyCode>97) )
{
window.event.returnValue=false;
alert("Please Enter Only Alphabets");
}
break;
}
case 'N': {
if ((window.event.keyCode<48 || window.event.keyCode>57))
{
window.event.returnValue=false;
alert("Please Enter Only Numeric Values");
}
break;
}
case 'AN':
{
if ((window.event.keyCode<48) ||(window.event.keyCode>57 &&
window.event.keyCode<65) || window.event.keyCode>122 ||
(window.event.keyCode>90 && window.event.keyCode<97))
{
window.event.returnValue=false;
alert("Please Enter Only Alpha Numeric Values");
}
break;
}
}
}
After writing this code in "Jscript.js" file, in "Default.aspx", include:
<script language="JavaScript" type="text/JavaScript" src="JavaScript/CFunc.js">
in the <head></head>
tag of your Default.aspx page. The work is almost done. Now just use "chkchars('AN','')
" for alphanumeric validation."chkchars('A','')
" for Alphabet validation, "chkchars('N','')
" for Numeric validation and to exclude some characters during validation, just add it in chakchars
function as"chkchars('AN','()/-')
" for validating (,),- and / in that textbox.
For example:
<asp:TextBox ID="textbox1" runat="server" onKeyPress="chkChars('AN','()-/')" ></asp:TextBox>
This example will allow only Alphanumeric Characters or (,),-,/.
Hope this will help you.