bring your forms up to date with css3 and html5 validation _ webdesigntuts+

21
Advertise Here Jim Nielsen on Jan 2nd 2013 with 89 Comments and 51 Reactions Tutorial Details Topic: HTML5 form validation, CSS3 Difficulty: Beginner Estimated Completion Time: 45 mins Let’s look at how to create a functional form which validates users’ data, client-side. With that done, we’ll cover prettying it up using CSS, including some CSS3! Republished Tutorial Every few weeks, we revisit some of our reader's favorite posts from throughout the history of the site. This tutorial was first published in November of 2011. Step 1: Conceptualization Functionality First we want to conceptualize what our form is going to look like and how it is going to function. For this example, let’s create a simple contact form that asks for the following information from the user: Name Email Website Message Bring Your Forms Up to Date With CSS3 and HTML5 Validation | Webd... http://webdesign.tutsplus.com/tutorials/site-elements/bring-your-forms-u... 1 of 21 01/08/2013 1:27 PM

Upload: bobaxhanque472

Post on 28-May-2017

221 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Bring Your Forms Up to Date With CSS3 and HTML5 Validation _ Webdesigntuts+

Advertise Here

Jim Nielsen on Jan 2nd 2013 with 89 Comments and 51 Reactions

Tutorial Details

Topic: HTML5 form validation, CSS3Difficulty: BeginnerEstimated Completion Time: 45 mins

Let’s look at how to create a functional form which validates users’ data, client-side. With that done, we’ll coverprettying it up using CSS, including some CSS3!

Republished Tutorial

Every few weeks, we revisit some of our reader's favorite posts from throughout the history of the site. Thistutorial was first published in November of 2011.

Step 1: Conceptualization FunctionalityFirst we want to conceptualize what our form is going to look like and how it is going to function. For thisexample, let’s create a simple contact form that asks for the following information from the user:

NameEmailWebsiteMessage

Bring Your Forms Up to Date With CSS3 and HTML5 Validation | Webd... http://webdesign.tutsplus.com/tutorials/site-elements/bring-your-forms-u...

1 of 21 01/08/2013 1:27 PM

Page 2: Bring Your Forms Up to Date With CSS3 and HTML5 Validation _ Webdesigntuts+

We want to make sure the user is entering the information correctly. To accomplish this, we will use HTML5′snew client-side validation techniques. What about users who don’t have HTML5 capabilities? You can simplyuse server-side validation, but that will be beyond the scope of this article.

Step 2: Conceptualization FormLet’s get an idea of what we want our form to look like by creating a rough mockup.

As you can see, the following elements make up our form:

Form TitleRequired fields notificationForm labelsForm inputsPlaceholder textForm field hintsSubmit Button

Now that we’ve specified which elements make up our form, we can create the HTML markup.

Step 3: HTML Starter CodeLet’s create our basic HTML markup from the form concept we created.

001 <!DOCTYPE html>

Bring Your Forms Up to Date With CSS3 and HTML5 Validation | Webd... http://webdesign.tutsplus.com/tutorials/site-elements/bring-your-forms-u...

2 of 21 01/08/2013 1:27 PM

Page 3: Bring Your Forms Up to Date With CSS3 and HTML5 Validation _ Webdesigntuts+

Up to this point, our HTML file will still appear blank in the browser. This is simply starter code for an HTML5page.

Step 4: HTML FormLet’s create the HTML form (we’ll leave the action method blank for now, since server-side validation will notbe covered in this tutorial):

Step 5: HTML Form ElementsTo keep our form content organized and structured, we’ll wrap our form elements (label, input, etc) in a list.So let’s start by creating the form header and our first input element:

002003004005006007008009010

<html><head> <meta charset="utf-8"> <title>HTML5 Contact Form</title> <link rel="stylesheet" media="screen" href="styles.css" ></head><body></body></html>

001002

<form class="contact_form" action="" method="post" name="contact_form"></form>

001002003004005006007008009010

<ul> <li> <h2>Contact Us</h2> <span class="required_notification">* Denotes Required Field</span </li> <li> <label for="name">Name:</label> <input type="text" name="name" /> </li></ul>

Bring Your Forms Up to Date With CSS3 and HTML5 Validation | Webd... http://webdesign.tutsplus.com/tutorials/site-elements/bring-your-forms-u...

3 of 21 01/08/2013 1:27 PM

Page 4: Bring Your Forms Up to Date With CSS3 and HTML5 Validation _ Webdesigntuts+

Form HintsAs seen in our mockup, we’re going to have formatting hints for the “email” and “website” fields. So we’ll addour hints under the input fields where necessary, and give them a class so we can style them later.

001002003004005

<li> <label for="email">Email:</label> <input type="text" name="email" /> <span class="form_hint">Proper format "[email protected]"</span></li>

Bring Your Forms Up to Date With CSS3 and HTML5 Validation | Webd... http://webdesign.tutsplus.com/tutorials/site-elements/bring-your-forms-u...

4 of 21 01/08/2013 1:27 PM

Page 5: Bring Your Forms Up to Date With CSS3 and HTML5 Validation _ Webdesigntuts+

The Remaining Input ElementsLet’s go ahead and create our remaining form elements, remembering to wrap each section in a list item.

001002003004005006007008009010011012

<li> <label for="website">Website:</label> <input type="text" name="website" /> <span class="form_hint">Proper format "http://someaddress.com"</span></li><li> <label for="message">Message:</label> <textarea name="message" cols="40" rows="6" ></li><li> <button class="submit" type="submit">Submit Form</button></li>

Bring Your Forms Up to Date With CSS3 and HTML5 Validation | Webd... http://webdesign.tutsplus.com/tutorials/site-elements/bring-your-forms-u...

5 of 21 01/08/2013 1:27 PM

Page 6: Bring Your Forms Up to Date With CSS3 and HTML5 Validation _ Webdesigntuts+

Step 6: Adding the Placeholder AttributeOne of the first improvements HTML5 brings to web forms (one you’re probably already familiar with) is theability to set the placeholder text. Placeholder text is displayed when the input field is either empty or not infocus.

Let’s add the placeholder attribute to our input elements. This will help the user understand what they shouldenter in each field.

Quick Tip: Style your placeholder TextHere’s a quick tip, if you want to style your placeholder text, there are some browser prefixes to help you:

Support for the placeholder attribute is pretty well established in modern browsers (except IE9, sorry). If youreally need to have it supported across all browsers, there are some javascript solutions you could look into.

001002003

<input type="text" name="name" placeholder="John Doe" /><input type="text" name="email" placeholder="[email protected]" /><input type="text" name="website" placeholder="http://johndoe.com/" required/>

001002003004005006

:-moz-placeholder { color: blue;}::-webkit-input-placeholder { color: blue;}

Bring Your Forms Up to Date With CSS3 and HTML5 Validation | Webd... http://webdesign.tutsplus.com/tutorials/site-elements/bring-your-forms-u...

6 of 21 01/08/2013 1:27 PM

Page 7: Bring Your Forms Up to Date With CSS3 and HTML5 Validation _ Webdesigntuts+

Step 7: Basic CSSLet’s add some basic CSS to give our form some structure. I’ll walk you through the rules:

Remove :focus StyleWebkit automatically adds some styling to input elements when they are in focus. Since we’ll be adding our ownstyles, we want to override these defaults:

Typographic StylesLet’s add some typographic styles to our form elements:

001 *:focus {outline: none;}

001002003

body {font: 14px/21px "Lucida Sans", "Lucida Grande", "Lucida Sans Unicode".contact_form h2, .contact_form label {font-family:Georgia, Times, "Times New Roman".form_hint, .required_notification {font-size: 11px;}

Bring Your Forms Up to Date With CSS3 and HTML5 Validation | Webd... http://webdesign.tutsplus.com/tutorials/site-elements/bring-your-forms-u...

7 of 21 01/08/2013 1:27 PM

Page 8: Bring Your Forms Up to Date With CSS3 and HTML5 Validation _ Webdesigntuts+

List StylesLet’s style our list elements to give our form some structure:

001002003004005006007008009010011012

.contact_form ul { width:750px; list-style-type:none; list-style-position:outside; margin:0px; padding:0px;}.contact_form li{ padding:12px; border-bottom:1px solid #eee; position:relative;}

Bring Your Forms Up to Date With CSS3 and HTML5 Validation | Webd... http://webdesign.tutsplus.com/tutorials/site-elements/bring-your-forms-u...

8 of 21 01/08/2013 1:27 PM

Page 9: Bring Your Forms Up to Date With CSS3 and HTML5 Validation _ Webdesigntuts+

Also, let’s add a slight border to the top and bottom sections of the form. We can accomplish this by using the:first-child and :last-child selectors. These select, as the names imply, the first and last elements in the<ul> list.

This adds some useful visual sectioning to our form. Keep in mind that these CSS selectors are not supported inolder browsers. Since this is not vital to key functionality, we’re rewarding our those who use current browsers.

001002003

.contact_form li:first-child, .contact_form li:last-child { border-bottom:1px solid #777;}

Bring Your Forms Up to Date With CSS3 and HTML5 Validation | Webd... http://webdesign.tutsplus.com/tutorials/site-elements/bring-your-forms-u...

9 of 21 01/08/2013 1:27 PM

Page 10: Bring Your Forms Up to Date With CSS3 and HTML5 Validation _ Webdesigntuts+

Form HeaderLet’s style the header section of our form. This includes the heading tag and the notification that informs usersthat the asterisk (*) indicates required fields.

001002003004005006007008009010

.contact_form h2 { margin:0; display: inline;}.required_notification { color:#d45252; margin:5px 0 0 0; display:inline; float:right;}

Bring Your Forms Up to Date With CSS3 and HTML5 Validation | Webd... http://webdesign.tutsplus.com/tutorials/site-elements/bring-your-forms-u...

10 of 21 01/08/2013 1:27 PM

Page 11: Bring Your Forms Up to Date With CSS3 and HTML5 Validation _ Webdesigntuts+

Form Input ElementsLet’s style all of our core form elements, the ones used to collect user information.

001002003004005006007008009010011012013014

.contact_form label { width:150px; margin-top: 3px; display:inline-block; float:left; padding:3px;}.contact_form input { height:20px; width:220px; padding:5px 8px;}.contact_form textarea {padding:8px; width:300px;}.contact_form button {margin-left:156px;}

Bring Your Forms Up to Date With CSS3 and HTML5 Validation | Webd... http://webdesign.tutsplus.com/tutorials/site-elements/bring-your-forms-u...

11 of 21 01/08/2013 1:27 PM

Page 12: Bring Your Forms Up to Date With CSS3 and HTML5 Validation _ Webdesigntuts+

Now, let’s add some extra visual CSS styles. Some of these are CSS3 styles that reward users who use modernbrowsers.

001002003004005006007008009010011012013014015016017018019020021022023024025026027028

.contact_form input, .contact_form textarea { border:1px solid #aaa; box-shadow: 0px 0px 3px #ccc, 0 10px 15px #eee inset; border-radius:2px;}.contact_form input:focus, .contact_form textarea:focus { background: #fff; border:1px solid #555; box-shadow: 0 0 3px #aaa;}/* Button Style */button.submit { background-color: #68b12f; background: -webkit-gradient(linear, left top, left bottom, from(#68b12f background: -webkit-linear-gradient(top, #68b12f, #50911e); background: -moz-linear-gradient(top, #68b12f, #50911e); background: -ms-linear-gradient(top, #68b12f, #50911e); background: -o-linear-gradient(top, #68b12f, #50911e); background: linear-gradient(top, #68b12f, #50911e); border: 1px solid #509111; border-bottom: 1px solid #5b992b; border-radius: 3px; -webkit-border-radius: 3px; -moz-border-radius: 3px; -ms-border-radius: 3px; -o-border-radius: 3px; box-shadow: inset 0 1px 0 0 #9fd574; -webkit-box-shadow: 0 1px 0 0 #9fd574 inset ;

Bring Your Forms Up to Date With CSS3 and HTML5 Validation | Webd... http://webdesign.tutsplus.com/tutorials/site-elements/bring-your-forms-u...

12 of 21 01/08/2013 1:27 PM

Page 13: Bring Your Forms Up to Date With CSS3 and HTML5 Validation _ Webdesigntuts+

Step 8: Add Some Interactivity with CSS3Let’s add a little bit of interactivity. We’ll make the field that is currently selected expand by adding somepadding.

029030031032033034035036037038039040041042043044045046047048049

-moz-box-shadow: 0 1px 0 0 #9fd574 inset; -ms-box-shadow: 0 1px 0 0 #9fd574 inset; -o-box-shadow: 0 1px 0 0 #9fd574 inset; color: white; font-weight: bold; padding: 6px 20px; text-align: center; text-shadow: 0 -1px 0 #396715;}button.submit:hover { opacity:.85; cursor: pointer;}button.submit:active { border: 1px solid #20911e; box-shadow: 0 0 10px 5px #356b0b inset; -webkit-box-shadow:0 0 10px 5px #356b0b inset ; -moz-box-shadow: 0 0 10px 5px #356b0b inset; -ms-box-shadow: 0 0 10px 5px #356b0b inset; -o-box-shadow: 0 0 10px 5px #356b0b inset;}

001002

.contact_form input:focus, .contact_form textarea:focus { /* add this to the already existing padding-right:70px;

Bring Your Forms Up to Date With CSS3 and HTML5 Validation | Webd... http://webdesign.tutsplus.com/tutorials/site-elements/bring-your-forms-u...

13 of 21 01/08/2013 1:27 PM

Page 14: Bring Your Forms Up to Date With CSS3 and HTML5 Validation _ Webdesigntuts+

Now for browsers that support it, let’s make the expansion of the field a smooth transition using CSS3.

Step 9: The required Attribute in HTML5Now it’s time for what we’ve all been waiting for: HTML5′s form handling tools.

Adding the required attribute to any input/textarea element will tell the browser that a value is required beforethe form can be submitted. Thus, a form cannot be submitted if a required field has not been filled out.

003 }

001002003004005006

.contact_form input, .contact_form textarea { /* add this to the already existing style */ -moz-transition: padding .25s; -webkit-transition: padding .25s; -o-transition: padding .25s; transition: padding .25s;}

Bring Your Forms Up to Date With CSS3 and HTML5 Validation | Webd... http://webdesign.tutsplus.com/tutorials/site-elements/bring-your-forms-u...

14 of 21 01/08/2013 1:27 PM

Page 15: Bring Your Forms Up to Date With CSS3 and HTML5 Validation _ Webdesigntuts+

So, let’s go ahead and add the required attribute to all of our form elements (because we want them all to befilled out).

Step 10: Styling required FieldsYou’ll probably notice that, visually speaking, nothing happened by adding the required attribute. We are goingto style required fields using CSS. For this example, we are going to add a red asterisk as a background image ineach required field. To accomplish this, we will want to first add some padding on the right side of our inputwhere the background image will be (this will prevent text overlap if the field entry is a long string):

Now we will use the CSS pseudo selector :required to target all the form elements with a required attribute. Imade a simple 16×16 pixel red asterisk icon in photoshop that will serve as the visual indicator of a requiredfield.

001002003004

<input type="text" name="name" required /><input type="text" name="email" required /><input type="text" name="website" required /><textarea name="message" cols="40" rows="6" required ></textarea>

001002003

.contact_form input, .contact_form textarea { padding-right:30px;}

001002003

input:required, textarea:required { background: #fff url(images/red_asterisk.png) no-repeat 98% center;}

Bring Your Forms Up to Date With CSS3 and HTML5 Validation | Webd... http://webdesign.tutsplus.com/tutorials/site-elements/bring-your-forms-u...

15 of 21 01/08/2013 1:27 PM

Page 16: Bring Your Forms Up to Date With CSS3 and HTML5 Validation _ Webdesigntuts+

What happens upon submission?Right now, different browsers will do different things when a form using HTML5 elements is submitted. Whenthe form is submitted, most browsers will prevent the form from being submitted and will display a “hint” to theuser, marking the first field that is required and has no value. Visual styling and support for these ‘bubble fields’is quite broad. Hopefully these behaviors will become standardized in the future.

You can see current browser support for the required attribute at quirksmode.

Quick Tip:You can actually style the bubble message somewhat in webkit using the following:

Step 11: Understanding New HTML5 typeAttributes and Client-Side ValidationHTML5 validation works according to the type attribute that is set within the form fields. For years HTML only

001002003

::-webkit-validation-bubble-message { padding: 1em;}

Bring Your Forms Up to Date With CSS3 and HTML5 Validation | Webd... http://webdesign.tutsplus.com/tutorials/site-elements/bring-your-forms-u...

16 of 21 01/08/2013 1:27 PM

Page 17: Bring Your Forms Up to Date With CSS3 and HTML5 Validation _ Webdesigntuts+

supported a handful of type attributes, such as type="text" but with HTML5 there are a over a dozen new inputtypes including email and url which we are going to use in our form.

By combining our input type attributes with the new required attribute, the browser can now validate theform’s data client-side. If a user’s browser does not support the new type attributes, such as type="email", itwill simply default to type="text". This is actually pretty amazing. Essentially you have backwardscompatibility in all browsers on earth, hooray!

So what if the browser does actually support the new type attributes? For desktop browsers there is no visualdifference (unless specified by custom CSS rules). A type="text" field looks the same as a type="email"

field. However, for mobile browsers, there is a difference when it comes to the user interface.

An Example: The iPhoneApple’s iPhone detects the form types and dynamically changes the on-screen keyboard by providingcontext-aware characters. For example, all email addresses require the following symbols: “@” and “.” So theiPhone provides those characters when the input type is specified to email.

Step 12: Changing the type AttributesWe already have our form fields set to the default type="text". But now we want to change the type attributeon our email and website fields to their corresponding HTML5 type.

Step 13: HTML5 ValidationAs mentioned before, HTML5 validation is based on your type attributes and it is on by default. There is nospecific markup required in order to activate form validation. If you wish to turn it off, you can use thenovalidate attribute like this:

Name FieldLet’s look at our first field that asks the user for his/her name. As described eariler, we’ve added thetype="text" attribute and the required attribute. This informs the web browser that this field is mandatory andit should validate the field as simply text. So as long as the user enters at least one character in that field, it will

001002

<input type="email" name="email" placeholder="[email protected]" required /><input type="url" name="website" placeholder="http://johndoe.com" required/>

001002003004

<form novalidate> <-- do not validate this form --> <input type="text" /></form>

Bring Your Forms Up to Date With CSS3 and HTML5 Validation | Webd... http://webdesign.tutsplus.com/tutorials/site-elements/bring-your-forms-u...

17 of 21 01/08/2013 1:27 PM

Page 18: Bring Your Forms Up to Date With CSS3 and HTML5 Validation _ Webdesigntuts+

validate.

Now we will create our own CSS to style field inputs that are considered valid and invalid by the browser. If youremember, we used :required in our CSS to style all input elements with a required attribute. Now, we canstyle our required fields that are either valid or invalid by adding :valid or :invalid to our CSS rules.

First, let’s style fields that are invalid. For this example, we only want to style the form as invalid when it is infocus. We’ll add a red border, red shadow, and red icon created in photoshop to indicate the invalid field.

Now, let’s create the rules that indicate the field is valid. We’ll add a green border, green shadow, and greedcheckmark icon made in photoshop. This will be applied to all valid fields whether they are in focus or not.

Now when you focus on a form field, the red invalid styling is shown. As soon as a single character has beenentered in the field, it is validated and green CSS styles are shown to indicate that fact.

Email and URL FieldsOur CSS styles and validation rules are already applied to the email field because we set the type and requiredattributes earlier.

Step 14: Introducing the HTML5 pattern AttributeUsing the type="email" attribute as an example, it appears that most browsers validate that field as *@* (anycharacter + the “@” symbol + any character). This is obviously not very limiting but it does prevent users fromentering spaces or values that are entirely wrong.

In the example of the type="url" attribute, it appears as though the minimum requirement for most browsers isany character followed by a colon. So, if you entered “h:” then the field would validate. This is not extremelyhelpful but it does prevent users from entering irrelevant information, such as their email or home address. Now,you could handle being more specific on with your input values in your server-side validation; however, we’regoing to talk about how to do that in HTML5.

001002003004005

.contact_form input:focus:invalid, .contact_form textarea:focus:invalid { /* when a field is background: #fff url(images/invalid.png) no-repeat 98% center; box-shadow: 0 0 5px #d45252; border-color: #b03535}

001002003004005

.contact_form input:required:valid, .contact_form textarea:required:valid { background: #fff url(images/valid.png) no-repeat 98% center; box-shadow: 0 0 5px #5cd053; border-color: #28921f;}

Bring Your Forms Up to Date With CSS3 and HTML5 Validation | Webd... http://webdesign.tutsplus.com/tutorials/site-elements/bring-your-forms-u...

18 of 21 01/08/2013 1:27 PM

Page 19: Bring Your Forms Up to Date With CSS3 and HTML5 Validation _ Webdesigntuts+

The pattern AttributeThe pattern attribute accepts a javascript regular expression. This expression is used, rather than the browserdefault, to validate the field’s value. So our HTML now looks like this:

Now our field will only accept values that start with “http://” or “https://” and one additional character. Theseregular expression patterns can be confusing at first, but once you take the time to learn them, your forms will beopen to a whole new world.

Step 15: Form Field Hints (CSS)Now let’s style our form hints that tell the user the format they should use when entering their information.

We set display:none because we are only going to show the hints when the user focuses on the input field. Wealso set our tooltips to default to our red invalid color, because they are always considered invalid until theproper information is entered in.

Using the ::before SelectorNow we want to add a little triangle to our hint boxes that help direct and guide the eye. This can be done usingimages, but in our case we are going to do it using pure CSS.

Because it is purely a presentational element that is not vital to the page’s functionality, we are going to add asmall triangle that points left using the ::before pseudo selector. We can do this by using one of the unicodegeometric shapes.

Normally we would use the HTML Unicode format to display these in our HTML (as shown in the imageabove). However, because we will be using the ::before CSS selector, we have to use the triangle’scorresponding escaped unicode when using the content:"" rule. Then we just use positioning to get it where wewant it.

001 <input type="url" name="website" placeholder="http://johndoe.com" required

001002003004005006007008009010

.form_hint { background: #d45252; border-radius: 3px 3px 3px 3px; color: white; margin-left:8px; padding: 1px 6px; z-index: 999; /* hints stay above all other elements */ position: absolute; /* allows proper formatting if hint is two lines */ display: none;}

001 .form_hint::before {

Bring Your Forms Up to Date With CSS3 and HTML5 Validation | Webd... http://webdesign.tutsplus.com/tutorials/site-elements/bring-your-forms-u...

19 of 21 01/08/2013 1:27 PM

Page 20: Bring Your Forms Up to Date With CSS3 and HTML5 Validation _ Webdesigntuts+

Using the + Adjacent SelectorFinally, we are going to use the CSS adjacent selector to show and hide our form field hints. The adjacentselector (x + y) selects the element that is immediately preceded by the former element. Since our field hintscome right after our input fields in our HTML, we can use this selector to show/hide the tooltips.

As you can see from the CSS, we also set the form hints to change colors along with the input’s border when afield is valid or invalid.

Step 16: Sit Back and Admire Your BeautifulHTML5 FormGo ahead and take a look at your final product!

ConclusionAs you can see, the new HTML5 form features are pretty neat! Everything is backwards compatible soincorporating these new features into your website won’t break anything.

HTML5 validation is coming closer to replacing client-side validation in helping users properly fill out theironline forms. However, HTML5 validation still does not replace server-side validation. For the time being, it’sbest to use both methods when handling user-submitted information. Thanks for reading!

002003004005006007

content: "\25C0"; /* left point triangle in escaped unicode */ color:#d45252; position: absolute; top:1px; left:-6px;}

001002003

.contact_form input:focus + .form_hint {display: inline;}

.contact_form input:required:valid + .form_hint {background: #28921f;} /* change form hint co

.contact_form input:required:valid + .form_hint::before {color:#28921f;} /* change form hint

ERROR

Bring Your Forms Up to Date With CSS3 and HTML5 Validation | Webd... http://webdesign.tutsplus.com/tutorials/site-elements/bring-your-forms-u...

20 of 21 01/08/2013 1:27 PM

Page 21: Bring Your Forms Up to Date With CSS3 and HTML5 Validation _ Webdesigntuts+

Tags: css3formhtml5validation

By Jim NielsenJim Nielsen considers himself a web designer at heart, though he often dabbles in other areas such as print andidentity design. He loves acquiring new knowledge and hopes to someday develop competency in a wide-arrayof disciplines including programming, mathematics, and even physics!

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more

Bring Your Forms Up to Date With CSS3 and HTML5 Validation | Webd... http://webdesign.tutsplus.com/tutorials/site-elements/bring-your-forms-u...

21 of 21 01/08/2013 1:27 PM