Pro HTML5 and CSS3 Design Patterns

(avery) #1
CHAPTER 20 ■ ALERTS

Form Validation


Problem You want to validate user input in forms and display the necessary alerts.


Solution Form validation has traditionally been done using JavaScript, e.g., there are several jQuery
plug-ins that offer form validation at
http://plugins.jquery.com/projects/plugins?type=20. HTML5 offers native validation
for forms and also adds a number of useful input types like e-mail, web addresses, date
pickers, and more. You can use this native validation mechanism to check user input and
print alerts.


Pattern^


HTML ^
Use type="email" to validate e-mail addresses, type="url" to validate web addresses,
type="number" to validate for e-mail addresses, etc.
Add the required string inside the input element to make it a required field.
Add the novalidate string inside the form element to avoid native form validation.
Use attributes min, max, step to fine-tune type="number".


Advantages Form validation is hard and error-prone, so having it performed natively by the browser and
being RFC-compliant in cases like e-mail, etc., is very helpful.


Tips Some mobile devices that don’t have a physical keyboard can recognize several of the
new HTML5 input types, and dynamically change the onscreen keyboard to optimize for
that kind of input. For example, when you use an iPhone and focus an input type="email"
element, you get an onscreen keyboard that contains a smaller-than-usual space bar, plus
dedicated keys for the “@” and “.” characters. Similarly for input type="number" you get a
number scroller, etc.
There are several more input types that the HTML5 specification defines, but browser
support varies. Unless you are developing for a specific platform (e.g., iOS devices), it is
probably wiser to continue using JavaScript validation and input widgets that are known to
work with older browsers.
Some forms of validations are notoriously hard to perform correctly even for browsers.
For example, Chrome validates the string foo@bar as a correct e-mail address.
Default validation alerts are ugly, but in the future it will be easy to add CSS style to them.
Chrome and Safari have recently added support for pseudo-selectors like ::-webkit-
validation-bubble{}, ::-webkit-validation-bubble-top-outer-arrow{}, ::-webkit-
validation-bubble-top-inner-arrow{}, and ::-webkit-validation-bubble-message{}.
At the time of this writing, Firefox has no way to style the error messages.
Similarly you might want to change the text of the error messages. Firefox has support
for the attribute x-moz-errormessage, which enables you to change the text of the error
message. The same can be accomplished in Chrome using CSS and the webkit-
validation-bubble-message.

Free download pdf