Sams Teach Yourself HTML, CSS & JavaScript Web Publishing in One Hour a Day

(singke) #1
ptg16476052

326 LESSON 12: Designing Forms


You can also specify the minimum number of characters the user must enter before the
form will submit with the minlength attribute. However, as of this writing this is only
supported in Chrome (and Android) and Opera web browsers.
To display text in the text control before the user enters any information, use the value
attribute. If the user is updating data that already exists, you can specify the current or
default value using value, or you can prompt the user with a value:
<input type="text" id="petname" size="15" maxlength="15" value="Enter Pet Name">
In this case, Enter Pet Name appears in the field when the form is rendered in the web
browser. It remains there until the user modifies it. It will also be submitted to the form
just like anything the user writes. If you want to make a suggestion as to what the user
should write, but you don’t want that value submitted with the other form data, you
should use the placeholder attribute:
<input type="text" id="petname" size="15" maxlength="15" placeholder="Fido">
This is particularly important on fields that are required. If there is a value set, the fields
will not validate as empty and will not trigger the automatic browser validation.

When you’re using the placeholder attribute, using a value
that’s larger than the size of the text control can confuse the user
because the text will appear to be cut off. Try to use only enough
information to make your point. Ensure that any placeholder text
is less than or equal to the number of characters you specified in
size.

CAUTION

HTML5 adds a number of new attributes on form controls to help browsers validate the
data before it is submitted to the form. The most important one is the required attri-
bute. This indicates that a form field must be filled out for the form to be submitted. It
is a Boolean attribute, so you just need to include the word required for the field to be
marked required:
<input id="name" required>
The pattern attribute provides a regular expression against which the control’s value
should be checked. It uses the JavaScript regex patterns. You should include the pattern
description somewhere on the page or in the input control (such as in the title attribute)
so that your customers know what the rules are. If you wanted someone to submit a part
number that has one digit followed by three uppercase letters, you would write
<label> Part number:
<input pattern="[0-9][A-Z]{3}" name="part"
title="A part number is a digit followed by three uppercase letters.">
</label>
Free download pdf