Saturday, December 21, 2024

HTML5 Forms: How To Use The New Email, URL, and Telephone Input Types

Off the top of your head, what would you say are some of the greatest challenges in working with HTML forms? I’ll give you a couple of mine: field validation and data formating. And now that I’m on the subject, I’d like to add tabbing order, autofocus and error handling.

You’ll be delighted to know that the new HTML5 spec deals with most of these common gripes. The only bad news is that browser support is still sketchy right now. But that’s OK because, as you’ll see here today, it doesn’t hurt anything to use the HTML5 attributes.

Well be starting with Input Field types, the work horse of the form business. Thanks to the type attribute it can play the role of a hidden field, toggle button, checkbox, radio button, password, or a single line text field, to name but a few. The authors of the HTML5 standard no doubt asked themselves “why stop there?” and added no less than 13 new input types! So, without further ado, let’s see what makes these new input types worth talking about.

HTML5’s Email Input Type

No need to explain what this is for. What does bear discussing is what a royal pain email addresses are to deal with. The established way to handle them is to allow free-form text entry and then run them through a Regular Expression. This presents a whole host of issues, the main one being using too strict a pattern. Rather than consult the official RFC822 email standard, most coders would rather guess at the requirements. The rules for email addresses are actually a lot more lenient (and yet complex) that most people assume. A RegExp can do the job, but validating an entire email address at once results in an expression so long and complex, that it should come with a “viewer discretion” advisory! Behold the 6,343 character behemoth! I dare you to try to decipher it. I double dog dare ya!

The Validation Process

When the user submits the form, the browser automatically performs RFC-compliant email validation, whether JavaScript is enabled or not, and displays a generic message in close proximity to the field in question:

Image 1

If you’d rather display your own message, you can provide one by calling the field’s setCustomValidity() function in JavaScript:

var emailField = document.getElementById("emailField");
emailField.setCustomValidity(emailField.value + " is invalid! Please try again.");

Testing for HTML5 Browser Support

Right now the email type is not supported by all the major browsers. Here’s what we’ve got at this time:

Image 2

Don’t let a lack of browser support deter you from using the email type. All browsers do share similar behavior in that they all default unknown types to text. This is useful to know because we can test the current browser’s capability and use JavaScript as a fallback. The trick is that the browser will only retain the type value you set if it supports that input type. Otherwise, it will ignore the value you set and leave the type property as “text”. Therefore, rather than test each type individually, you can test for all your HTML5 input fields against the text type:

function inputTypeIsSupported(field) {
	return (field.type == "text");
}

var passedValidation = true;

var emailField = document.getElementById("emailField");
if (!inputTypeIsSupported(emailField)) {
   //call our fallback function
    passedValidation = validateEmail(emailField);
}

GUI Tailoring for Different Input Types

In addition to providing field validation, Mobile devices such as iPhone, iPod touch, and iPad present tailored on-screen keyboards for numeric input, phone numbers, as well as web and email addresses. For example, the keyboard for email fields contains dedicated keys for the obligatory ‘@’ and ‘.’ characters.

HTML5’s Web Address Input Type

Web URLs are also inherently difficult to validate. At least they were, until HTML5 came along with the new ‘url’ input type. Browsers will still treat the field as a regular text box, with the addition that declaring the field as the url type will cause it to be validated and mobile devices to replace the space bar with a period, a forward slash, and a “.com” virtual keys.

HTML5’s Phone Number Input Type

Input fields that accept phone numbers use the “tel” type. Due to inherent variances in phone number formats, the tel input type does not conform to any specific pattern. Rather, browsers treat it as a regular, single-line text input field, the result of which is that no attempt is made by the browser to validate the field. The main advantage to using this type of field then is to optimize the keyboard on mobile devices. Nonetheless, since validation should be performed on telephone fields, there is a new attribute that can help you to enforce your preferred format. It’s called the pattern element. When you include it, the browser will validate the field contents against the Regular Expression assigned to the pattern attribute. Here is some HTML markup to validate a phone number field:

<input type='tel' pattern='[\+]\d{2}[\(]\d{2}[\)]\d{4}[\-]\d{4}' title='Phone Number (Format: +99(99)9999-9999)'> 

In addition to the telephone (tel) type, the pattern attribute also works with the text, search, url, email, and password input types. We’ll be getting to some a those a little later on.

Image 3

Conclusion

I don’t know if you’ll ever be able to throw all your JavaScript form validation out the window, but HTML5 has sure made it a whole lot easier! Stay tuned for the next installment of “What’s New in HTML5 Forms”, when we’ll be looking at more great new input types, including the number and date/time.

Robert Gravelle
Robert Gravelle
Rob Gravelle resides in Ottawa, Canada, and has been an IT guru for over 20 years. In that time, Rob has built systems for intelligence-related organizations such as Canada Border Services and various commercial businesses. In his spare time, Rob has become an accomplished music artist with several CDs and digital releases to his credit.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles

Featured