HTML and CSS Reference
In-Depth Information
If you wanted a number between 1 and 99, you could set
maxlength
to 2; this would stop people from entering 100 but not
—
1. And if
you were looking to limit people to a value between 1 and 50,
maxlength
would be even more useless.
In
HTML5
, you can use the
min
and
max
attributes on the number input
type. You already saw these attributes on the range control, where they
specify the limits of the slider. On the number control, they trigger an
error when the user tries to submit the form:
<input type="number" max="10"
name="exnumber">
The
min
attribute works exactly the same
way:
<input type="number" min="4"
name="exnumber">
There's also help if the format you
require is somewhat more exotic. You
can use the
pattern
attribute to supply a
regular expression that is then used to
validate the field. This example is taken
from the
HTML5
spec:
<input type="text" name="partno"
pattern="[0-9][A-Z]{3}"
title="A part number is a digit
followed by three uppercase
letters.">
If the validation fails, the browser dis-
plays the value of the
title
attribute, so
you should include some information
there that will help the user in filling
out the form.