19

I want to create a input field for phone number. I am creating input field using JavaScript dynamically.

<input type="text" id="phone" name="phone">

How to restrict users to type only 10 digit numbers in order to get a phone number.

Vivek Kumar
  • 1,204
  • 4
  • 15
  • 35
  • possible duplicate of [validating 10 characters, can only be numbers, then redirecting to a web address](http://stackoverflow.com/questions/8011291/validating-10-characters-can-only-be-numbers-then-redirecting-to-a-web-address) – niksvp Oct 18 '13 at 08:54
  • @Hariharan `size` doesn’t restrict the input field. – David Hellsing Oct 18 '13 at 08:56
  • maxlength should be used. – Hariharan Oct 18 '13 at 09:01
  • I have validation code in jquery but its not working because I have used javascript to create input text field. – Vivek Kumar Oct 18 '13 at 09:06
  • If this is created using JavaScript, then it is natural, and rather trivial, to do the checking with JavaScript. What have you tried? The difficult part is what to do (and which message to issue) when the input is not acceptable. On the other hand, it is a good principle to accept at least spaces, too, in phone number input. – Jukka K. Korpela Oct 18 '13 at 09:07
  • My phone number is 0033 5 61 ** ** **. 13 digits including the country code. How would you handle people from different countries, or are they just not able to use your form? – Niet the Dark Absol Oct 18 '13 at 09:23
  • Right now, it is for only country, I will modify it later for more than one. – Vivek Kumar Oct 18 '13 at 09:28

21 Answers21

30

try this

<input type="text" name="country_code" title="Error Message" pattern="[1-9]{1}[0-9]{9}"> 

This will ensure

  1. It is numeric
  2. It will be max of 10 chars
  3. First digit is not zero
Vinay Lodha
  • 2,185
  • 20
  • 29
  • it is not working when the type is not "text", maybe that's the issue – Wenuka Jan 05 '18 at 17:36
  • 1
    It works AWESOME but here in Australia numbers start from '0'... @Wenuka how can I make the above element accept first digit be a '0'? – Jim Apr 25 '18 at 11:21
  • maybe try this pattern "[0]{1}[0-9]{9}" – Vinay Lodha Apr 25 '18 at 13:09
  • yes, [0]{1}[0-9]{9} is fine. Use an online "regex online tester" to check whether your regular expression is working fine. – Wenuka Apr 26 '18 at 11:35
  • 1
    hey @Wenuka and Vinay, `[1]{1}[0-9]{9}` would be fine for 10 digits.. what would it be if I needed it to be of **at least** `n` length, should I use an asterisk like `[1]{1}[0-9]{n-1}[0-9]{*}`? – Harshith Rai Apr 09 '19 at 06:33
15

Use maxlength

<input type="text" maxlength="10" />
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
iJade
  • 23,144
  • 56
  • 154
  • 243
11

You can use maxlength to limit the length. Normally for numeric input you'd use type="number", however this adds a spinny box thing to scroll through numbers, which is completely useless for phone numbers. You can, however, use the pattern attribute to limit input to numbers (and require 10 numbers too, if you want):

<input type="text" maxlength="10" pattern="\d{10}" title="Please enter exactly 10 digits" />
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • 1
    Okay I will try this but I have solved my problem, I also posted my own answer too. – Vivek Kumar Oct 18 '13 at 09:30
  • What browser are you using? Old versions of IE don't support it. Then again it shouldn't matter, because all validation should be server-side anyway. – Niet the Dark Absol Oct 18 '13 at 13:08
  • If you mean that it still lets you type non-numeric characters, then that's normal. It's non-invasive, in that it lets the user type what they want, and informing them inline when they enter invalid data. You should never block the user from typing what they want. For instance, that's why YouTube comments (and even comments here) will just tell you how many characters over the limit you are, instead of just preventing you from typing. That way, you can type out what you mean in full, and then work on shortening it to fit. – Niet the Dark Absol Oct 18 '13 at 14:06
  • [JSFiddle demo](http://jsfiddle.net/RXVvx/), and [my result](http://prntscr.com/1y3w31) when tying in a non-numeric value and clicking the Submit button. – Niet the Dark Absol Oct 18 '13 at 14:51
  • type="text" then this will allow alphabets aslo. who needs alphabets in phone number – Heemanshu Bhalla Feb 15 '20 at 03:40
  • @HeemanshuBhalla "You can, however, use the `pattern` attribute to limit input to numbers" – Niet the Dark Absol Feb 15 '20 at 12:44
5

Well I have successfully created my own working answer.

<input type="text" id="phone" name="phone" onkeypress="phoneno()" maxlength="10">

as well as

    <script>        
           function phoneno(){          
            $('#phone').keypress(function(e) {
                var a = [];
                var k = e.which;

                for (i = 48; i < 58; i++)
                    a.push(i);

                if (!(a.indexOf(k)>=0))
                    e.preventDefault();
            });
        }
       </script>
Vivek Kumar
  • 1,204
  • 4
  • 15
  • 35
2

Add a maxlength attribute to your input.

<input type="text" id="phone" name="phone" maxlength="10">

See this working example on JSFiddle.

Lewis
  • 789
  • 8
  • 20
2

HTML

<input type="text" name="fieldName" id="fieldSelectorId">

This field only takes at max 10 digits number and do n't accept zero as the first digit.

JQuery

jQuery(document).ready(function () {
      jQuery("#fieldSelectorId").keypress(function (e) {
         var length = jQuery(this).val().length;
       if(length > 9) {
            return false;
       } else if(e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
            return false;
       } else if((length == 0) && (e.which == 48)) {
            return false;
       }
      });
    });
Pradosh
  • 69
  • 7
1

use a maxlength attribute to your input.

<input type="text" id="phone" name="phone" maxlength="10">

See the fiddle demo here Demo

1
$(document).on('keypress','#typeyourid',function(e){
if($(e.target).prop('value').length>=10){
if(e.keyCode!=32)
{return false} 
}})

Advantage is this works with type="number"

1

This is what I use:

<input type="tel" name="phoneNumber" id="phoneNumber" title="Please use a 10 digit telephone number with no dashes or dots" pattern="[0-9]{10}" required /> <i>10 digits</i>

It clarifies exactly what is expected in the entry and gives usable error messages.

0

whereas you could use maxLength on the input, and some javascript validation, it will still be necessary to do server side validation anyway.

Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
0

HTML

<input type="text" id="youridher" size="10">

Use JQuery,

SIZE = 10
$(document).ready(function() {
      $("#youridher").bind('keyup', function() { 
            if($("#youridher").val().length <= SIZE && PHONE_REGEX) {
                return true;
            }
            else {
                return false;
            }  
      });
});
Nilesh
  • 2,407
  • 1
  • 12
  • 20
  • This uses jQuery without mentioning it, and it does not check whether the characters are digits. And it does not work when data is pasted rather than typed. – Jukka K. Korpela Oct 18 '13 at 09:08
0

maxlength restrict the number of digits which cannot be more than the desired digits but it accepts less than the desired digits. If mobile No maxlength="10" it will not accept 11 but may accept anything upto 10

0

Here all of the above outputs are giving a 10 digit number, but along with that the input field is accepting characters also, which is not the full solution. In order to set the 10 digit numbers only, we can use an input tag along with that type as number, and in that we can remove the up-down array by writing some small code in css which is shown below along with the input tag.

 <input name="phone" maxlength="10" pattern="[1-9]{1}[0-9]{9}" class="form-control" id="mobile"  placeholder="Enter your phone Number" type="number">


input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button { 
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
    margin: 0; 
}
ekhumoro
  • 115,249
  • 20
  • 229
  • 336
0

simply include parsley.js file in your document and in input element of mobile number enter this

data-parsley-type= "number" data-parsley-length="[10,10]" data-parsley-length-message= "Enter a Mobile Number"

you can change the message according to your requirement you also need to initialize parsley.js file in your document by writing

 <script type="text/javascript">

        $(document).ready(function() {
            $('form').parsley();
        });
    </script>   

---above code in your document.***

0

The snippet below does the job as expected!

<input type="text" name="AUS" pattern="[0-9]{10}" title="You can enter only 10 digits..." />


//type="text" <!-- always -->
//name="AUS" <!-- for Australia -->
//pattern="[0-9]{10}" <!-- 10 digits from 0 to 9 -->
//title="You can enter only 10 digits..." <!-- Pops a warning when input mismatches -->
Jim
  • 407
  • 1
  • 11
  • 24
0

How to set a textbox format as 8 digit number(00000019)

string i = TextBox1.Text;
string Key = i.ToString().PadLeft(8, '0');
Response.Write(Key);
ivcubr
  • 1,988
  • 9
  • 20
  • 28
0
  <input type="text" name='mobile_number' pattern=[0-9]{1}[0-9]{9}>
  • 1
    Code without any comments is a bad habit. Even in a question as simple as this. What if the OP is a newbie and does not know what is regex and cannot understand your code – Simas Joneliunas Jan 01 '20 at 13:40
0

Please find below code if you want user to restrict with entering 10 digit in input control

<input class="form-control  input-md text-box single-line" id="ContactNumber" max="9999999999" min="1000000000" name="ContactNumber" required="required" type="number"  value="9876658688">

Benefits -

  1. It will not allow to type any alphabets in input box because type of input box is 'number'

  2. it will allow max 10 digits because max property is set to maximum possible value in 10 digits

  3. it will not allow user to enter anything less than 10 digits as we want to restrict user in 10 digit phone number. min property in code is having minimum possible value in 10 digits so it will tell user to enter valid 10 digit value not less than that.

Heemanshu Bhalla
  • 3,603
  • 1
  • 27
  • 53
0

<label for="name" class="form-label" style="width:50%;">Mobile No:<input type="text" class="form-control" id="phone" name="mobile" pattern="\d{10}" title="Please enter exactly 10 digits" maxlength="10" required/></label>

This code will validate your contact form for non-numerical data entry. It will show an error message to the user when nonnumerical data is entered and fewer than 10 number is entered.

0

setInterval(function() {

  original = document.getElementById("displayResult").value;

  if (original.length > 10) {
    lastCharRemove =
      original.slice(0, original.length - 1);
    document.getElementById('displayResult').value = lastCharRemove;

  }
}, 100);
<input type="phone" placeholder="10 digit allowed" name="displayResult" id="displayResult" />
Sigurd Mazanti
  • 2,098
  • 1
  • 8
  • 24
0

$(document).ready(function($) {  
  $("#tax_no").keypress(function (e) {
    var charCode = (e.which) ? e.which : e.keyCode;
    var length = $(this).val().length;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
      return false;
    }
    if(length > 9) {
      return false;
    }

  });
});
<input type="text" class="woocommerce-Input woocommerce-Input--text input-text" name="nip_num" id="tax_no" />
  • You should add explanation. – Super Kai - Kazuya Ito Jun 15 '23 at 07:14
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 15 '23 at 17:51