[javascript] How to restrict user to type 10 digit numbers in input element?

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.

This question is related to javascript html css

The answer is


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.***


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


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; 
}

use a maxlength attribute to your input.

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

See the fiddle demo here Demo


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 -->

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.


  <input type="text" name='mobile_number' pattern=[0-9]{1}[0-9]{9}>

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>

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" />

whoever is checking this post in 2020, they can use <input inputmode="tel"> for phone numbers (10 digit), <input inputmode="numeric" maxLength={5}> for numeric type and restrict to only 5 digits.


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);

Use maxlength

<input type="text" maxlength="10" />

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.


$(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"


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;
       }
      });
    });

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;
            }  
      });
});

Add a maxlength attribute to your input.

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

See this working example on JSFiddle.


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


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width