HTML and CSS Reference
In-Depth Information
The required attribute
The simplest form of validation is to mark a field as required. In
HTML5
this is done by adding the
required
attribute. If an input is
marked as required, the browser shouldn't allow the form to be submit-
ted until the user has provided a value.
This image shows what happens when a
text input is marked as required and the
user tries to submit the form without
entering a value:
<input type="text" required
name="myrequiredfield">
You can add the
required
attribute to any
type of input:
<input type="date" required
name="myrequireddate">
As the image shows, the results of not
entering a value are the same in both
examples.
Note that a
name
attribute is included in the example; this
will label the field's value when it's sent to the server. The
automatic validation occurs when the form is submitted,
so you need a submittable form for these examples to work.
The min, max, and pattern attributes
The only native validation built into
HTML4
for the
text
input is the
maxlength
attribute. It allows you to specify the maximum number of
characters the user is allowed to enter. This is somewhat useful for
things like dates and phone numbers that have a well-defined length,
but it's not much use for anything else.