How To add a min and max length verification to a

2019-03-03 01:07发布

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?

1条回答
Summer. ? 凉城
2楼-- · 2019-03-03 01:49

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);
}
查看更多
登录 后发表回答