Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C# ASP.NET
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 26-Sep-11 23:58pm
Edited 27-Sep-11 1:14am
v3
Comments
hitech_ssc at 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..
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 9

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.
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 7

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!
  Permalink  
v4
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

you can do it in two ways
1.javascript
2.ajax
 

using javascript
 
<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>
<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>
  Permalink  
v9
Comments
member60 at 28-Jun-12 7:02am
   
my 5!
Abhishek Pant at 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
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

restrict user to enter only numbers
 
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
 
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;
}
}
  Permalink  
v4
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 8

without alert you can prevent your textbox......
 
try this...
 

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
  Permalink  
v4
Comments
MohsinAhmad at 23-Nov-12 5:25am
   
how to print 1 to 10 number in asp .net
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 6

hi,
 
Here I tried some code for your requirement.try this you can understood What I did
 
<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
  Permalink  
v3
Comments
Member 9177280 at 28-Jun-12 5:25am
   
it is gud but when we long press the button it allows the characters.
Muralikrishna8811 at 28-Jun-12 5:28am
   
yeah change that key event onkeyup to onkeydown
Member 9177280 at 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 at 28-Jun-12 5:52am
   
Did you check my latest update which i developed in Jquery its working fine
in all browsers
Muralikrishna8811 at 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>
V!jAy pAnT at 29-Jun-12 8:03am
   
it is not working ...... plz help ..!
Muralikrishna8811 at 29-Jun-12 8:04am
   
check jquery files are refereing or not
V!jAy pAnT at 29-Jun-12 8:19am
   
ya its refering.. but nothing is happening i used breakpoint also to see it but could'nt understand....
Muralikrishna8811 at 29-Jun-12 8:21am
   
place alert in document ready method to check its working or not
V!jAy pAnT at 29-Jun-12 8:32am
   
$(document).ready(function () {
$("#txtpincode").live('keydown', function () {
alert("hi");
});
});
 
even this is also not working...........
Muralikrishna8811 at 29-Jun-12 8:35am
   
$(document).ready(function () {
alert("hi");
$("#txtpincode").live('keydown', function () { }); });
 
this code working? i mean alert working or not?
V!jAy pAnT at 29-Jun-12 8:39am
   
ya it's working but i hv to run the code in keydown event...
Muralikrishna8811 at 29-Jun-12 8:40am
   
if that wrks means keydown events must be wrks its jquery so cross-browser
V!jAy pAnT at 29-Jun-12 8:46am
   
i checked it wid firefox & chrome both ....... but keydown event is not working .. i thing prob is wid $("#txtpincode").live('keydown', function ()
line so plz check it once more..
Muralikrishna8811 at 29-Jun-12 8:47am
   
post code which u used ?
V!jAy pAnT at 29-Jun-12 8:52am
   
$(document).ready(function () {
// alert("hi");
$('#txtpincode').live('keydown', function () {
 

if (parseInt(e.keyCode) > 47 && parseInt(e.keyCode) < 58) {
if (parseInt($(this).val().length) <= 6) {
 
}
else {
e.preventDefault();
}
}
else {
e.preventDefault();
}
});
});
Muralikrishna8811 at 28-Jun-12 5:43am
   
Hi I changed code check it once
which is simple in Jquery
Member 9177280 at 28-Jun-12 5:54am
   
thanks for this ...... but i m new in jquery can u tell me how can we use jquery...
Muralikrishna8811 at 28-Jun-12 5:55am
   
Yeah Sure
latest code works for you right?
Muralikrishna8811 at 28-Jun-12 5:57am
   
Jquery is simple and powerfull
and its just collection of javascript methods(javascript Library)
Member 9177280 at 28-Jun-12 6:57am
   
thnks Muralikrishna8811... i got it, now it is working fine but little bit prob is still there when we long prssing the number ......try & check
Muralikrishna8811 at 28-Jun-12 7:00am
   
I checked it its working fine
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 10

Hi,
1.To Allow alphanumerics
  Regex rgx = new Regex("^[a-zA-Z0-9_]*$");
2. for 10 numbers
var phoneFormat = /^\+?\d{1,3}(-|)?\d{3,5}(-|)?\d{1,10}$/;
 
Thanks
www.alacraft.com.au
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

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:
 
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
<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>
  Permalink  
v3
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 4

Hi,
 
you can put this expression to validate the text input:
 
    ^((\+)?(\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.
  Permalink  
v3
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 5

try with following
 
TextBox1.Attributes.Add("onkeydown", "isNumericKeyStroke()");
check me[^]
  Permalink  

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

  Print Answers RSS
0 OriginalGriff 490
1 Maciej Los 299
2 BillWoodruff 174
3 /\jmot 170
4 Suraj Sahoo | Coding Passion 150
0 OriginalGriff 8,484
1 Sergey Alexandrovich Kryukov 7,407
2 DamithSL 5,639
3 Maciej Los 5,159
4 Manas Bhardwaj 4,986


Advertise | Privacy | Mobile
Web02 | 2.8.1411023.1 | Last Updated 7 Mar 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100