Click here to Skip to main content
15,507,147 members
Please Sign up or sign in to vote.
1.50/5 (3 votes)
See more:
1) How to restrict user to enter only numbers in textbox using javascript.
2) How to restrict user to enter only 10 digits(mobile number) in textbox using javascript.
3) Or how to restrict user to enter only alphanumeric in textbox using javascript.
Posted
Updated 28-Apr-22 7:16am
v3
Comments
hitech_s 28-Sep-11 3:21am    
may i know who and why down voted my answer...
your question is changing time to time, in the begining you asked for only numbers after that changed question to restrict to 10 digits..

All these scenarios can easily be handed by using this small javascript framework. You will only need to call the functions and nothing else.

A Tiny Javascript Framework for Common Validation Scenarios.[^]

It has all the required functions, you can even change them as per your needs.

YOu might want to use them in combination with MAxlength property of textboxes and some custom regular expressions.
 
Share this answer
 
1) & 3) Use AJAXControlToolkit's FilteredTextBoxExtender Control.
2) Only 10 digits:
Use the RegularExpressionValidator Control for that!
Just set the ValidationExpression property of the Control as:
ValidationExpression="\d{10}"

This will do the task!
 
Share this answer
 
v4
you can do it in two ways
1.javascript
2.ajax


using javascript

XML
<script type="text/javascript">

   function numbersonly()
   {
   var data=document.getElementById('<%=TextBox1.ClientID %>').value;
   var filter=/^[a-zA-Z0-9]+$/;
    if(!filter.test(data))
       {
       alert("Please enter alphanumeric only");
       document.getElementById('<%=TextBox1.ClientID %>').value="";
       document.getElementById('<%=TextBox1.ClientID %>').focus();
       return false;
       }
       else if(data.Length!=10)
       {
       alert("Please enter 10 digits");
       return false;
       }
       else
       return true;
   }
   </script>

XML
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
   <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="javascript:return numbersonly();"/>




using ajax

registering :-
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>


<asp:TextBox ID="txtPhoneNo" runat="server" class="txtfeild" MaxLength="10"/>
                                                    <cc1:FilteredTextBoxExtender ID="txtPhoneNo_FilteredTextBoxExtender" runat="server"
                                                        Enabled="True" TargetControlID="txtPhoneNo" FilterMode="ValidChars" FilterType="Numbers">
                                                    </cc1:FilteredTextBoxExtender>
 
Share this answer
 
v9
Comments
member60 28-Jun-12 7:02am    
my 5!
Abhishek Pant 24-Oct-12 9:12am    
Does it is possible to restrict the same for windows based application in c#?
also my 5 to above answer
restrict user to enter only numbers

C#
function NumOnly(var1) {
            var num = document.getElementById(var1).value;
            var dot = 0;
            for (n = 0; n < num.length; n++) {
                digit = num.charCodeAt(n) >= 48 && num.charCodeAt(n) <= 57 || num.charCodeAt(n) == 46 || num.charCodeAt(n) == 45;
                if (!digit) {
                    alert('Enter Numbers Only');

                }
            }
            document.getElementById('<%=txtMobile.ClientID %>').value = "";
            document.getElementById(var1).focus();

        }


call this function in textbox onblur event


restrict user to enter only 10 digits(mobile number) in textbox

set
Maxlength="10"

maxlength is property of textbox
for this no need of javascript.


restrict user to enter only alphanumeric in textbox

C#
function validate(){
var usrid=document.getElementById("txtUserid"); //txtUserid-->ID of textbox
var alphanum=/^[0-9a-bA-B]+$/; //This contains A to Z , 0 to 9 and A to B
if(usrid.value.match(alphanum)){
return true;
}else{
alert(Put a Valid Userid Name);
return false;
}
}
 
Share this answer
 
v4
without alert you can prevent your textbox......

try this...


C#
function pin() {
            pincode = "<%=txtpincode.ClientID %>";
            if (parseInt(event.keyCode) > 47 && parseInt(event.keyCode)<58) {

                    var str = new String();
                    str = document.getElementById(pincode).value;
                    if (parseInt(str.length) > 6) {
                        document.getElementById(pincode).value = str.substring(0, str.length - 1);
                       }
                    }
            else {
                var str = new String();
                str = document.getElementById(pincode).value;
                document.getElementById(pincode).value = str.substring(0, str.length - 6);
                document.getElementById(pincode).value = "";
            }
            return true;
        }





Try this it will help you............without alert you can prevent the textbox to avoid typing the character by user...
one thing more use keyup event for this..
all will b well
v!z
 
Share this answer
 
v4
Comments
MohsinAhmad 23-Nov-12 5:25am    
how to print 1 to 10 number in asp .net
hi,

Here I tried some code for your requirement.try this you can understood What I did

HTML
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"  runat="server">
    <title></title>
    <script src="Scripts/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
    <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script language ="javascript" >
        $(document).ready(function () {
            $('.numeric10').live('keydown', function (e) {

                if (parseInt(e.keyCode) > 47 && parseInt(e.keyCode) < 58) {
                    if (parseInt($(this).val().length) <= 10) {

                    }
                    else {
                        e.preventDefault();
                    }
                }
                else {
                    e.preventDefault();
                }
            });
        });
    </script>
</head>
<body>
    <form id="form1"  runat="server">
    <div>
     <input type ="text" id="txtmbno" class="numeric10" />    
 
    </div>
    </form>
</body>
</html>


I hope you understood What I did

All the Best
 
Share this answer
 
v3
Comments
V!jAy pAnT 28-Jun-12 5:25am    
it is gud but when we long press the button it allows the characters.
Muralikrishna8811 28-Jun-12 5:28am    
yeah change that key event onkeyup to onkeydown
V!jAy pAnT 28-Jun-12 5:50am    
still it is not working type a character than type a number after that again type a character it is allowing ..i.e it seems like alphanumeric...... but i want restriction on typing the characters .....

Thanks
Muralikrishna8811 28-Jun-12 5:52am    
Did you check my latest update which i developed in Jquery its working fine
in all browsers
Muralikrishna8811 28-Jun-12 5:52am    
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<script src="Scripts/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script language ="javascript" >
$(document).ready(function () {
$('.numeric10').live('keydown', function (e) {

if (parseInt(e.keyCode) > 47 && parseInt(e.keyCode) < 58) {
if (parseInt($(this).val().length) <= 10) {

}
else {
e.preventDefault();
}
}
else {
e.preventDefault();
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type ="text" id="txtmbno" class="numeric10" />

</div>
</form>
</body>
</html>
C#
function NumOnly(var1) {
            var num = document.getElementById(var1).value;
            var dot = 0;
            for (n = 0; n < num.length; n++) {
                digit = num.charCodeAt(n) >= 48 && num.charCodeAt(n) <= 57 || num.charCodeAt(n) == 46 || num.charCodeAt(n) == 45;
                if (!digit) {
                    alert('Enter Numbers Only');

                }
            }
            document.getElementById('<%=txtMobile.ClientID %>').value = "";
            document.getElementById(var1).focus();

        }


or
Only Number validation in Textbox of ASP.NET Using Regular Expression validator
Only numbers can enter into that Textbox

We can use Regular expression validator for this:

XML
In the validation expression property keep ^\d+$.

<asp:TextBox ID="TextBox1" runat="server" Style="z-index: 100; left: 259px; position: absolute;
top: 283px" ValidationGroup="check"></asp:TextBox>

<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="TextBox1"
ErrorMessage="Please Enter Only Numbers" Style="z-index: 101; left: 424px; position: absolute;
top: 285px" ValidationExpression="^\d+$" ValidationGroup="check"></asp:RegularExpressionValidator>


For entering alpha numeric only
XML
<script type="text/javascript">
function checkkey(obj)
{ var re = /^[a-zA-Z_0-9]$/;
alert(re.test(obj.value));
if (! re.test(obj.value))
{ alert("Please enter alphanumeric only");
}
}
</script>
 
Share this answer
 
v3
Hi,

you can put this expression to validate the text input:

C#
^((\+)?(\d{2}[-]))?(\d{10}){1}?$


This is the validation expression of regular expression control. and set the

Control to validate-- property to the textbox where you want to input the value.

This Pattern is to Validate Mobile Number with 10 digit Number and Countrycode as Optional.
 
Share this answer
 
v3
try with following

TextBox1.Attributes.Add("onkeydown", "isNumericKeyStroke()");

check me[^]
 
Share this answer
 
if (mob.value == "") {
               alert("Please Enter Mobile Number");
               mob.focus();
               return false;
           }

           if (mob.value.length != 10) {
               alert("Please Enter 10 digit Mobile Number");
               mob.focus();
               return false;
           }
           var IndNum = /^[789]\d{9}$/;
           if (IndNum.test(mob.value) == false) {
               alert("Please enter Correct Mobile Number");
               mob.value = "";
               mob.focus();
               return false;
           }
 
Share this answer
 

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