user8492465
user8492465

Reputation:

How To add a min and max length verification to a number field?

I have the code for a number field:

<label for="Phone">Phone Number</label><br/>
<input id="Phone" name="Phone"class="form-control" type="tel"         pattern="^\d{3}\d{3}\d{4}$" maxlength="10"  minlength="10"  required >

However that doesn't limit to only numbers and only one format works i want to do something like:

<input name="Phone" type="number"  class="form-control"     placeholder="Phone Number" maxlength="10"  minlength="10"     required="required"/>

and that code does not limit the max and min lengths! How do i get the lengths to work?

Upvotes: 1

Views: 121

Answers (1)

clabe45
clabe45

Reputation: 2454

From the mozilla docs:

If the value of the type attribute is text, email, search, password, tel, or url, this attribute specifies the minimum number of characters (in Unicode code points) that the user can enter. For other control types, it is ignored.

That means that this attribute does not work as expected for a number input.

Here's one way you can define your own length-validator (of course you can write your own ;) ):

numberInput.addEventListener('input', function() {
    this.value = this.value.substring(0, MAX_LENGTH);
}

Upvotes: 2

Related Questions