HTML Input type number is not working with maxlength

15.4k Views Asked by At

I'm using below html tag and not able to get the restrictions on numbers, I need user to enter 12 digit only however as per HTML tag by default 'maxlength' does not work with <input type ="number">, I tried min and max tag, it did not help either.

Could you share if any way to do it in HTML only?

<input type="number" name="Aadhar" maxlength="12" placeholder="xxxx-xxxx-xxxx" pattern="[0-9]{4}-[0-9]{4}-[0-9]{4}" required>
6

There are 6 best solutions below

1
On

enter image description here

Use max instead of maxlength

<input type="number" name="Aadhar" max="12" placeholder="xxxx-xxxx-xxxx" pattern="[0-9]{4}-[0-9]{4}-[0-9]{4}" required>

When the user will click on Submit Button It will show that the value should be less than 12. This can be only used inside a form.

0
On

Max length will not work with <input type="number". Maybe you can read this click here to read more to resolve ur problem

1
On

You can try this.

function numOnly(id) {
    // Get the element by id
    var element = document.getElementById(id);
    // Use numbers only pattern, from 0 to 9 with \-
    var regex = /[^0-9\-]/gi;
    // Replace other characters that are not in regex pattern
    element.value = element.value.replace(regex, "");
}
<input type="text" id="number" oninput="numOnly(this.id);" name="Aadhar" maxlength="14" placeholder="xxxx-xxxx-xxxx" pattern="[0-9]{4}-[0-9]{4}-[0-9]{4}" required/>

0
On

Unfortunately, maxlength attribute is not supported for inputs that are type number. Therefore, the best approach is to use JS. Please refer to the following documentation and they might provide some clarity.

0
On

Please use this.

<input type="text" name="Aadhar" maxlength="12" placeholder="xxxx-xxxx-xxxx" pattern="\d*" required>

It worked to me.

0
On

Try to use type="tel" and maxlength