How to validate an input type number to accept only numbers?

Asked

Viewed 26 times

2

I am wanting to configure the input number of Html5 to accept only numbers, but it is accepting the letter "and" and also ",."

I’m doing it this way:

<label for="txtHora">Hora limite</label>
<input type="number" name="txtHora" id="txtHora" value="" maxlength="2" min="0" max="59" pattern="[0-9]{2}" class="form-control form-control-sm numeros data">

How can I leave only numbers? Why are you accepting these characters?

  • 1

    He accepts e and . because vc can type numbers in scientific notation - ex: 2.5e3 to the 2500 number. But that depends on the browser, if I’m not mistaken Firefox lets you type anything (and the field becomes invalid). If you want to use the pattern, will have to use type=text, for the type=number does not support this attribute: https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/pattern

  • Dude this input is for you to just mark time? Time does not have . or ,... You should be worried about the : think not?

  • @hugocsl in this case then I do not need to worry about the ":" because only matter the part of the time even, which will be typed by the user.

  • @hkotsubo helped yes, I understood that Pattern only serves to validate when the form is sent, in my case it would be to prevent something invalid from being typed. Thank you for your attention, thank you for the information you have given me, I will change here and make a script to prevent something unwanted to be typed in the field.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.