Click here to Skip to main content
15,890,123 members
Please Sign up or sign in to vote.
2.50/5 (2 votes)
Hello Frnds,

I have a Textbox on my Registration Form. The user Must enter only numbers into it BUT not alphabets.

the numbers lenght must be only 4 digits like 2005.

If the user enters alphabets, a message should be displayed "Please enter numbers only"

Please help me, which validation should be used, to do this.

Thanks.
Posted

You Can use it by two ways:-

1. Javascript
just add this script on page's HTML side
JavaScript
<script type="text/javascript">
function checking()
{
  var check1 = document.getElementById("<%=yourtextboxid.ClientID %>").length;
  if(var<>4)
  {
        alert('Please Enter Only 4 digit no.');
        return false;
  }
   else
    {
   return true;
    }
}

//this function is stopping the albhabet values has to be entered
function CheckNemericValue()
        {      
        if((event.keyCode >= 48 && event.keyCode <= 57) )
        {
        event.keyCode = event.keyCode; 
        }
        else
        {
        alert("Only Numbers are allowed");
        event.keyCode = 0;
        return false
        }
        }
</script>

and on page load event
JavaScript
protected void Page_Load(object sender, EventArgs e)
{
//this will invoke your javascript function on keypress event of textbox
yourtextboxid.Attributes.Add("onkeypress", "return CheckNemericValue(event);");
}

and on Button just add this javascript function like this.
JavaScript
<asp:button id="Button1" runat="server" text="Add" onclientclick="return checking()" onclick="Button1_Click" xmlns:asp="#unknown" />

this will help you.

and the
2. By validation controls

use
ASP.NET
<asp:regularexpressionvalidator id="RegularExpressionValidator1" runat="server" errormessage="Please Enter numeric Value Which contains 4 Digits Only" controltovalidate="yourtextboxid" setfocusonerror="True" validationexpression="^([0-9]{4})$" validationgroup="validation" xmlns:asp="#unknown">


You can also set text box's maximum length=4. so the user can't input more than 4 digit.//this is optional

tell me if for any error.

Mark it as Answer if it help you.
 
Share this answer
 
v4
Attach a range validator to that textbox and specify the maximum length as 4.
 
Share this answer
 
v2
Hi,
You can use RegularExpression validator as posted above which validates on the server side.
If you need it on client side you can user the below expression
^[0-9]+$

Thanks
Buy Lace
 
Share this answer
 
Comments
Nagy Vilmos 7-Jul-12 15:17pm    
I for the spam link.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900