Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Input type for HTML form for integer

Tags:

html

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> 
like image 447
John Avatar asked Jul 02 '12 23:07

John


2 Answers

<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.

like image 179
Kivi Shapiro Avatar answered Sep 28 '22 01:09

Kivi Shapiro


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).

like image 37
Brett Zamir Avatar answered Sep 28 '22 02:09

Brett Zamir