The code below is from an HTML form. If the input is supposed to be an integer, do I need to change the "type'?
<div class="friend2title"> <label for="url">Add points:</label> </div> <div class="friend2field"> <input name="state" type="text" id="state" maxlength="150"> </div>
<input type="number" step="1" ...
By adding the step
attribute, you restrict input to integers.
Of course you should always validate on the server as well. Except under carefully controlled conditions, everything received from a client needs to be treated as suspect.
This might help:
<input type="number" step="1" pattern="\d+" />
step
is for convenience (and could be set to another integer), but pattern
does some actual enforcing.
Note that since pattern
matches the whole expression, it wasn't necessary to express it as ^\d+$
.
Even with this outwardly tight regular expression, Chrome and Firefox's implementations, interestingly allow for e
here (presumably for scientific notation) as well as -
for negative numbers, and Chrome also allows for .
whereas Firefox is tighter in rejecting unless the .
is followed by 0's only. (Firefox marks the field as red upon the input losing focus whereas Chrome doesn't let you input disallowed values in the first place.)
Since, as observed by others, one should always validate on the server (or on the client too, if using the value locally on the client or wishing to prevent the user from a roundtrip to the server).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With