Search code examples
htmlvalidationattributes

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


I am pretty new in HTML 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 represent a number.

Can I specify in some way that this number has to be composed by exactly 11 digits? How can I do it using HTML attributes?


Solution

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