Sunday, February 7, 2010

Allowing only alphabets or numbers in the textbox

Place two text boxes on the page one to validate numbers and other to validate alphabets.

<asp:TextBox id="txtNumber" runat="server" onkeypress= "validateNumber()"/>

<asp:TextBox id="txtAlpha" runat="server" onkeypress= "validateAlphabet()"/>

Place the below javascripts to validate number and alphabet, first javascript will allow to enter only 0 to 9 and second javascript will allow to enter only a-z and A-Z

<script language="javascript" type="text/javascript">

function validateNumber()
{
if(!(event.keyCode >= 45 && event.keyCode <= 57))
{
event.returnValue=false;
}
}

function validateAlphabet()
{
if(!(event.keyCode >= 65 && event.keyCode <= 90) && !(event.keyCode >= 97 && event.keyCode <= 122))
{
event.returnValue=false;
}
}



Happy Coding!

No comments:

Site Meter