This is an excerpt from the HTML5 Solutions: Essential Techniques for HTML5 Developers book by Apress (where I'm one of the author).
Solution 4-8: Creating custom input types using regular expressions
Regular expressions provide a powerful, concise, and flexible means for matching strings of text, such as
particular characters, words, or patterns of characters. A regular expression is written in a formal language
that can be interpreted by a regular expression processor, which is a program that either serves as a
parser generator or examines text and identifies parts that match the provided specification. See Wikipedia
for more information: http://en.wikipedia.org/wiki/Regular_expression.
HTML5 allows you to check the user’s inputs and to match the input values against a regular expression.
What’s involved
The code that you needed to write to use regular expressions with previous versions of HTML was
as follows:
<input type="text" name="ssn"
onblur="if (!^\d{3}-\d{2}-\d{4}$this.value) alert(this.title+'\nAn error occurred. Please
verify your data.');" title="The Social Security Number"/>
On the onblur event of the input element, a JavaScript statement is executed. It controls the pattern to be
applied to the data in the field, and it provides an error message if the validation wasn’t successful.
With HTML5, a new attribute is available that allows you to associate a pattern of characters via regular
expressions to a text input to be applied as validation of the data inserted in the field. The markup for this
is really simple:
<input type="text" name="ssn" pattern="(!^\d{3}-\d{2}-\d{4}$"
The value specified in the pattern attribute must match the JavaScript pattern production as described in
this document: www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf.
Note: Matching the JavaScript pattern implies that the regular expression language used
for this attribute is the same as that used in JavaScript, except that the pattern attribute
must match the entire value—not just any subset. (This is somewhat as if it implied a
^(?: at the start of the pattern and a )$ at the end.)
To provide the user with a description of the pattern, or an error reporting on the field if an invalid value is
entered, you can use the attribute title:
<input type="text" name="ssn"
pattern="(!^\d{3}-\d{2}-\d{4}$"
title="The Social Security Number" />
How to build it
In the following solution, we use a regular expression to validate the American zip code:
(\d{5}([\-]\d{4})?)
This expression is inserted in the pattern attribute of the text input. Here is the complete code:
<!DOCTYPE html>
<html>
<head>
<title>
Solution 4-8: Creating custom input types using regular expressions
</title>
</head>
<body>
<form id="myForm">
<fieldset>
<legend>Solution 4-8: Creating custom input types using regular expressions</legend>
<label> Insert a valid American Zip code:
<input type="text" name="ssn"
pattern="(\d{5}([\-]\d{4})?)"
title="Zip Code" />
</label>
<p><input type="submit" value="Check Zip code" /> </p>
</fieldset>
</form>
</body>
</html>
When you execute the file in a browser, such as Opera, that supports the pattern attribute, and click the
submit button of the form.
The browser provides control over the validity of the data that matches the regular expression specified in the attributes pattern. If it fails, it returns an error message.
Expert tips
Not all browsers support this powerful attribute yet. Fortunately, there is a library that fills this gap:
Google’s Web Forms 2, which you can find at the following address: https://github.com
/westonruter/webforms2.
The project, as described on the site, is a cross-browser implementation of the WHATWG Web Forms 2.0
specification. If the library realizes when it is loaded that the browser is not compatible with some of the
new HTML5 functions, such as the pattern attribute, it applies its own methods instead.
You need to import the JavaScript wbforms2_src.js library using the script tag to use the library:
<script type="text/javascript" src="YOUR_FOLDER/webforms2_src.js"></script>
It is also important for the webforms2.css and webforms2-msie.js both to be located in the same directory
as webforms2.js or webforms2-p.js (whichever you decide to use).
The implementation has been tested and should work in the following browsers:
Mozilla Firefox 1.0.8
Mozilla Firefox 1.5.0.9
Mozilla Firefox 2
Internet Explorer 6
Internet Explorer 7
Safari 2.0.4
Safari 3 (Windows)
Opera 9 (native experimental implementation)
Google I/O begins in less than 48 hours! Even if you're not attending in person, you can still get all the news via the live stream.
Larry Page should not be on stage as he's sick (with no voice)!
The first day's keynote will be at 9:30 a.m. PDT on June 27, and the second day's is at 10:00 a.m. PDT on June 28. Lots of cool Chrome and HTML5 sessions that you really don't want to miss will also be streamed live. Other sessions will be recorded and made available soon after the conference.
To keep up to date with the relevant HTML5 sessions, follow +Google Chrome Developers (http://g.co/PlusChromeDev).
Thanks to Peter (Google Chrome Developer Relations) for the info :)
This is an excerpt from the HTML5 Solutions: Essential Techniques for HTML5 Developers book by Apress (where I'm one of the author).
HTML5 Solution 4-7: Validating form controls
In the first solution in this chapter, we showed you how to use built-in mechanisms to validate an e-mail
input type. This function is new to HTML5.
When you work with forms, validation of data is definitely an important aspect that may require quite a lot
of effort. We often resort to mixed validation systems. With JavaScript or AJAX frameworks (such as
JQuery, Dojo, and MooTools), you can make client-side validations and you can develop server-side
validating procedures with server-side languages (PHP, Python, Java, and so on).
Thanks to the insertion of new attributes in HTML5, you can delegate some data verification functions to
the browser and reduce the effort required for these kinds of operations (at least from the client side).
What’s involved
Some form controls inherit validation systems without having to write any code. In Solution 4-1, we showed
how the validation mechanism for an e-mail type text input works automatically by only declaring the
markup:
<input type="email" />
The same can be said for the URL and number markups, <input type="url"> and <input
type="number">.
There is, however, an attribute that can be used to specify the presence of a compulsory field in a form,
which you can’t leave empty.
To request this kind of validation, you need to use required in the input control:
<input type="text" required />
This attribute is Boolean. When specified, the element is required.
Browsers that support this attribute display an error message or insert a red border on the field that
generated the error and won’t submit the form.
How to build it
For this solution, modify the code from Solution 4-2 by adding the required attribute for two of the three
fields.
Here is the complete code:
<!DOCTYPE html>
<html>
<head>
<title>
Solution 4-7: Validating form controls
</title>
</head>
<body>
<form id="myForm">
<fieldset>
<legend>Solution 4-7: Validating form controls </legend>
<label for="name">Name</label>
<input id="name" name="name" type="text" placeholder="Insert your first name" required
/><br/>
<label for="email">Email</label>
<input id="email" name="email" type="email" placeholder="Insert your email" required
/><br/>
<label for="blog">Blog</label>
<input id="blog" name="blog" type=url placeholder="Insert your blog"/><br/>
<p>
<input type="submit" value="Submit"/>
</p>
</fieldset>
</form>
</body>
</html>
If you open the file and try sending the form without any data in the two required fields, the browser will
not allow you to submit the form if the mandatory fields are empty,
One important aspect regarding the usability of the form suggests that the mandatory fields have to
provide the user with a visual or textual clue informing them of the required data. One convention is to
insert an asterisk (*) symbol next to the required field.
You can add some text and graphic clues with CSS by using the pseudo-classes :valid, :invalid,
:optional, and :required.
A form element is :required or :optional if a value for it is, respectively, required or optional before the
form to which it belongs is submitted.
You can learn more about this topic by reading this article: www.w3.org/TR/css3-ui/#pseudo-validity. All
you have to do is use these pseudo-classes to make the fields more stable. Change the code from before
by adding a <style> block, as follows:
<!DOCTYPE html>
<html>
<head>
<style>
#myForm .required:after { content: " * "; color:red;}
#myForm input:required { background:red; color:white; }
</style>
<title>
Solution 4-7: Validating form controls
</title>
</head>
<body>
<form id="myForm">
<fieldset>
<legend>Solution 4-7: Validating form controls </legend>
<label for="name">Name</label>
<input id="name" name="name" type="text" placeholder="Insert your first name" required
/><br/>
<label for="email">Email</label>
<input id="email" name="email" type="email" placeholder="Insert your email" required
/><br/>
<label for="blog">Blog</label>
<input id="blog" name="blog" type="url" placeholder="Insert your blog"/><br/>
<p>
<input type="submit" value="Submit"/>
</p>
</fieldset>
</form>
</body>
</html>
In the new style block, we have declared two CSS statements. The first acts on the required class and
adds text after the selector with the pseudo-class :after; in our case, a * next to the label element:
#myForm .required:after { content: " * "; color:red;}
The second statement, on the other hand, uses the required pseudo-class on the input tag changing the
background color to red:
#myForm input:required { background:red; }
The only change required in the code is in the tag label, with which you need to associate the :required
class using the attribute class, so it will insert the *:
<label for="name">Name</label>
<input id="name" name="name" type="text" placeholder="Insert your first name" required
/><br/>
<label for="email">Email</label>
<input id="email" name="email" type="email" placeholder="Insert your email" required
/><br/>
Once you’ve saved the file and executed it in a browser, you'll see that the CSS pseudo-classes is applied
to the fields.
Expert tips
The built-in validation mechanism of the fields in HTML5 will be applied automatically by default. However,
there are contexts in which it is necessary to use JavaScript to create more complex and robust validation
routines.
In such cases, it is necessary to override the default validation system of the browser.
The novalidate attribute specifies that the form should not be validated when submitted:
<form id="myForm" novalidate>
<fieldset>
<legend>Solution 4-7: Validating form controls </legend>
<label for="name">Name</label>
<input id="name" name="name" type="text" placeholder="Insert your first name" required/><br/>
<label for="email">Email</label>
<input id="email" name="email" type="email" placeholder="Insert your email" required
/><br/>
<label for="blog">Blog</label>
<input id="blog" name="blog" type="url" placeholder="Insert your blog"/><br/>
<p>
<input type="submit" value="Submit"/>
</p>
</fieldset>
</form>
You can specify this attribute at the form level, as in the example above, or within the following <input>
types: text, search, URL, telephone, e-mail, password, date pickers, range, and color.
This is an excerpt from the HTML5 Solutions: Essential Techniques for HTML5 Developers book by Apress (where I'm one of the author).
It was already possible to send any kind of file from your computer to a remote server with the older
versions of HTML by using the form, and the <input type = file> in particular.
This form control, however, had the limit of being able to send only one file at a time. If the user wanted to
upload a photo album and thus send several photos, the developer had to use other technologies, such as
Flash or JavaScript, to provide this feature.
Now, with HTML5 and with the addition of an attribute, it is possible to manage everything without using
any external language.
HTML5 introduces a new attribute to the file input type, multiple, to improve file upload usability. Multiple
is a Boolean attribute that indicates whether the user should be allowed to specify more than one value.
It’s specified inline to the markup input tag:
<input type="file" multiple />
This attribute is supported by the latest versions of Safari, Chrome, Firefox, Internet Explorer, and Opera.
The input control will be rendered according to the browser, with a simple text input with a button on the
side to select the files (e.g., Opera), or with only a button (e.g., Chrome and Safari).
Other browsers, such as Chrome, use the same button label used for a simple file input type. However,
they specify the number of selected files for the user (but not their file names, as Opera and Firefox do).
To carry out a multiple selection, the user will use the SHIFT or CTRL or CMD keys after having clicked on
the Choose Files or Add Files button.
How to build it
From a technical point of view, the only thing you need to be aware of to allow the user to upload multiple
files is to add the multiple attribute in the declaration of the tag file input type.
Here is a complete example:
<!DOCTYPE html>
<html>
<head>
<title>
Solution 4-5: Sending multiple files
</title>
</head>
<body>
<form id="myForm">
<fieldset>
<legend>Solution 4-5: Sending multiple files</legend>
<label>Upload one or more files:</label>
<input type="file" name="multipleFileUpload" multiple />
<br />
</fieldset>
</form>
</body>
</html>
Expert tips
The files that the user selects will have to be sent to the server and processed using server-side language.
Some programming languages, such as PHP, require you to add brackets to the name attribute of the tag
to send multiple files:
<input name="filesUploaded[]" type="file" multiple />
By doing so, PHP will construct an array data type, which will contain the uploaded files on the server. If
you don’t specify the brackets, the programming language will process the files in order and only provide
the last file in your script.
It's about to be released the CSS3 Solutions book. Together with the HTML5 Solutions, this book provides a collection of solutions to all of the most common CSS3 problems. Every solution contains sample code that is production-ready and can be applied to any project.
CSS3 brings a mass of changes, additions, and improvements to CSS across a range of new modules. Web designers and developers now have a whole host of new techniques up their sleeves, from working with colors and fonts accurately, to using media queries to ensure correct styling across a multitude of devices. But all of these new technologies bring more tags to learn and more avenues for things to go wrong. CSS3 Solutions provides a collection of solutions to all of the most common CSS3 problems. Every solution contains sample code that is production-ready and can be applied to any project.
Real-world solutions for everyday CSS3 development, saving hours of frustration. Problems covered include:
Comtaste has just published the new dates for the Developing Rich Web Apps with HTML5 training course:
This is the outline of the HTML5 corso:
Structure of a HTML5 page
Using the new DOCTYPES
Replacing the presentational Markup
Avoid with security vulnerabilities with character encoding
Global Values
Structuring the page using:
section
header
footer
nav
article
Using block semantic elements: aside, figure, and dialogue
Detecting if a browser supports a HTML 5 feature
Using the Modernizr open source library
HTML5 Markups
The new Horizontal Rule
Using the IFRAME
Using the EMBED tag
Creating empty lists
Linking Heading, paragraphs, blockquotes
Using the AREA tag
Using the media attrbiutes for the A and AREA tags
Semantic HTML5 Markup
Understanding Microdata
Using the itemprop and itemscope
Creating a custom vocabulary
Using the microdata with the DOM API
Understanding Link types and relations
The header and hgroup elements
Connecting images with their captions
Using the article element
Date and Times elements
Adding tangent content
HTML5 Forms
Understanding the new input types
Using the built-in validation for email input type
Using an url input type
Using a spinner control
Working with the data in your Form
Adding a slider to your Form with the range input type
Sending multiple files
Creating a Google's suggest-like autocomplete with the data list component
Validating form controls
Creating custom input types using regular expressions
Setting placeholder text in an input field
Using the built-in validation for email addresses formats
Creating Date and Time Controls
Create a complete form
Applying CSS to a Form
Working with Video and Audio
Embedding a video in a web page
Checking for video format support
Detecting Video support across browser
Creating a video controller
Preloading videos
Creating a custom seekbar for a video
Understanding the Codecs
Encoding videos in different sources
Using multiple source video elements
Opening a video in Fullscreen
Applying CSS to a Video element
Adding a mask to videos
Using the new AUDIO element
Understanding the Canvas APIs
Understanding the CANVAS APIs
Detecting the Canvas and Canvas text support
Understanding the standard screen-based coordinate system
Pixel manipulations
Applying shadows and blurring
Animating canvas
Drawing with the Canvas 2D APIs
How to draw with HTML 5: Using the Canvas 2D APIs
Using paths and coordinates
Drawing shapes: rectangle and circle
Filling shapes with solid colors
Using gradients to fill shapes
Drawing texts in a canvas
Working with relative font sizes to draw text on a canvas
Saving a shape as a PNG file
HTML5 Communication APIs
Understanding the PostMessage API
Checking for postMessagi API browser support
Cross-documents messaging and CORS
Sending messages between windows and iframe
Using the Server-Event technologies for writing real-time web applications
Creating independent pieces of code to communicate directly
Running code in different browsing contexts using Message channels
Uploading files using the XMLHttpRequest Level 2
Checking for the XMLHttpRequest Level 2 cross-origin browser support
Working with WebSocket
Understanding the COMET approach
Checking for WebSocket browser support
Establishing a websocket connection
Handling websocket events
Full-duplex messaging between client and server
Parsing and constructing WebSocket URLs
Understanding the data framing
Using the WebSocket Interfae for Javascript programming
Using a WebSocket server with the WebSocket API
Using the Geolocation APIs
Understanding the Geolocation APIs
Using the navigator object
Using the position object
Working with coordinates
Handling error with the PositionError
Getting the current position
Using the geo.js open source library
Local Storage
Understanding the Occasionally Connected Applications
Checking for HTML5 Storage support
Declaring a Manifest for your page
Using the ApplicationCache object
The ApplicationCache events
Bypassing the cache
Accessibility in HTML5
Creating skip links with the nav element
Creating accessible tabular data
Form accessibility
Captioning and annotations using video elements
The Canvas interface elements
Using the ARIA project
I've just discovered that the HTML5 Solutions book published on June 2011 has already got three great reviews on Amazon.com.
That's a great result that pay all the effort spent on this book.
Thanks to all readers !!
One of the reasons why I've stopped blogging is due the hard work behind writing books.
This is my last one:
HTML5 SolutionsEssential Techniques for HTML5 Developers
HTML5 brings the biggest changes that HTML has seen in years. Web designers and developers now have a whole host of new techniques up their sleeves, from displaying video and audio natively in HTML, to creating realtime graphics directly onto a web page without the need for a plugin. But all of these new technologies bring more tags to learn and more avenues for things to go wrong. HTML5 Solutions provides a collection of solutions to all of the most common HTML5 problems. Every solution contains sample code that is production ready and can be applied to any project.
Real-world solutions for everyday HTML development, saving hours of frustration. Problems covered include:
Web developers and designers wanting practical advice on making HTML5 sites work.
Recently I've presented at the Codemotion conference talking about HTML5. It's been a great conference and my speech was followed by hundreds people.
At the end of the speech I've had a quick interview with Wired.it and today it has been published on the portal (it's in italian language):
http://gadget.wired.it/news/mondo_computer/html-5.html
From the WhatWG blog you can read the following announcement: HTML is the new HTML5.
It means that from now on the technology is not versioned and instead WhatWG just has a living document that defines the technology as it evolves.
Because the specification is now a living document, we are today announcing two changes:
http://whatwg.org/html
. (We will also continue to maintain the Web Applications 1.0 specification that contains HTML and a number of related APIs like Web Storage, Web Workers, and Server-Sent Events.)