How can I specify the exact number of digits that an user have to insert into an input field?

AndreaNobili picture AndreaNobili · Feb 11, 2016 · Viewed 14.5k times · Source

I am pretty new in HTML5 and I have the following problem. Into a page I have an input tag like this:

<input id="codiceFiscaleEnte" class="form-control" name="numeroProtocollo" type="number" th:value="*{codiceFiscaleEnte}" required="required"></input>

and I have to do some validation on it.

So I know that the required="required" attribute means that the user have to insert a value for this field and that the type="number" specify that this value have to reprsent a number.

Now my problem is: can I specify in some way that this number have to be composed by exactly 11 digits? How can I do it using HTML5 attributes?

Answer

Marcos P&#233;rez Gude picture Marcos Pérez Gude · Feb 11, 2016

Use pattern:

<input type="text" name="numeroProtocollo" required pattern="[0-9]{11}">

It allows only numbers with a minimum and maximum length of 11

Test it:

https://jsfiddle.net/oegjdszx/1/