Tuesday, December 9, 2014

HTML5 Form Attributes : required, placeholder, autofocus & pattern


HTML5 offers over a dozen new input types, along with several fresh attributes.
Used together, they make web forms far more powerful and flexible, while eliminating or reducing much of the previous need for JavaScript and PHP to validate user data.
Placeholder text

The first is a feature that has been a feature of forms for some time, albeit one created via JavaScript: placeholder text within an <input>.

<input type=text name=firstname id=firstname placeholder=”Enter your first name here”>

Note that a <label> tag should still be present: most screen readers for the blind do not yet read placeholder text.
placeholder replaces previous techniques that have used a combination of CSS and/or JavaScript to create the same effect. You can style the placeholder text in some, but not all, browsers, using proprietary CSS:

input::-webkit-input-placeholder, input:-moz-placeholder { color: #999; }
autofocus

We have always been able to control the order of focus in a form with the tab index attribute, but outside of JavaScript there was no way to make a particular field active by default, with the cursor inside it… and even the JavaScript solutions were a little tacky and prone to error. Now we can use the following:

<input type=text name=firstname id=firstname autofocus=true>

Please be careful with this: “stealing focus” from users is, generally speaking, a poor interface decision.
required

Up until now there has been no way in HTML to insist that certain fields be filled out before the user can submit a form. That has been one of the primary purposes of form validation with PHP and/or JavaScript. HTML5 can now build that insistence into a form:

<form action=formhandler.php>

<label for=firstname accesskey=f>First name</label>

<input type=text name=firstname id=firstname required>

<label for=lastname accesskey=l>Last name</label>

<input type=text name=lastname id=lastname>

<input type=submit>

</form>

In Firefox, pressing the submit button without entering information into the first field will result in the browser displaying the following:HTML5 required field
pattern

Perhaps the most exciting addition to HTML5 forms is the ability to add your own regular expressions directly into the HTML via the pattern attribute, such as for a Canadian postal code:

<input type=text name=postcode id=postalcode pattern=”^[ABCEGHJKLMNPRSTVXY]{1}d{1}[A-Z]{1}([ -])*d{1}[A-Z]{1}d{1}$” required>

Firefox will validate the text entered into the field against a pattern and show that the field is wrong if they do not match.

1 comment: