An alternative to the solutions presented is to block only the submission of the form with attributes HTML5 validation , not the user input.
In fact, there is no way to ensure that the data entered is in accordance with what is planned, if the user wants to make a noise, he will do so. If you have Javascript disabled in the browser and you have a validation through script, it would pass smoothly. If he wants to inspect the source code of the page and modify some attribute in the HTML or a function in a JS file that deals with the validation, it would also pass a good one.
That's why there should be other checks on the server, this subject has already generated a question about validation efficiency only in < in> client-side . Validation in the client is only an attempt to save resources and avoid performing requests at random to the server.
Returning to the validation attributes, one of the main advantages is to eliminate the need to use Javascript to validate fields. On the other hand, there is the good bad old story of limited support in some browsers, so my answer may not be the best solution depending on the users who access (or can access) your page.
1st solution: type='text'
with attribute pattern
One way is to set the attribute pattern
field to accept only numbers.
<input type='text' pattern='\d*'/>
2nd solution: Use a field of type number
Semantically, this would be the best option to create a field that only accepts numbers, no doubt. But here comes the compatibility issue and support for the type='number'
fields sucks .
<input type='number'/>
You can even use the :invalid
> to inform the user what type of data is expected in that field:
p {
color: #ea6153;
display: none
}
input:invalid + p {
display: inline
}
<input type='text' pattern='\d*'/>
<p>Ei! Este campo só pode ter números.</p>
Completing
Validations with HTML is something recent, this explains the limited support in some browsers. But I look forward to the implementations of this feature since joining the specification . , we just need to give it some more time.
In the same way that we had to use Javascript in the past to make animations, however simple - today we do it elegantly with CSS3 only - we will soon be using HTML only to limit the entries in one field.
Can I Use? is a great site to track the compatibility of a feature . There are libraries like
Modernizr that are there to detect these features and help the developer make use of