Bring Your Forms Up to Date With CSS3 and HTML5 Validation

Bring Your Forms Up to Date With CSS3 and HTML5 Validation

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

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


Step 2: Conceptualization Form

Let’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 Title
    Required fields notification
  • Form labels
  • Form inputs
    Placeholder text
  • Form field hints
  • Submit Button

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


Step 3: HTML Starter Code

Let’s create our basic HTML markup from the form concept we created.

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

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


Step 4: HTML Form

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

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

Step 5: HTML Form Elements

To 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:

<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>

Form Hints

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

<li>
	<label for="email">Email:</label>
	<input type="text" name="email" />
	<span class="form_hint">Proper format "name@something.com"</span>
</li>

The Remaining Input Elements

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

<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>

Step 6: Adding the Placeholder Attribute

One of the first improvements HTML5 brings to web forms (one you’re probably already familiar with) is the ability to set the placeholder text. Placeholder text is displayed when the input field is either empty or not in focus.

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

<input type="text" name="name" placeholder="John Doe" />
<input type="text" name="email" placeholder="john_doe@example.com" />
<input type="text" name="website" placeholder="http://johndoe.com/" required/>

Quick Tip: Style your placeholder Text

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

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

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


Step 7: Basic CSS

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

Remove :focus Style

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

*:focus {outline: none;}

Typographic Styles

Let’s add some typographic styles to our form elements:

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

List Styles

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

.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;
}

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 in older browsers. Since this is not vital to key functionality, we’re rewarding our those who use current browsers.

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

Form Header

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

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

Form Input Elements

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

.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;}

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

.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), to(#50911e));
	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 ;
	-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;
}

Step 8: Add Some Interactivity with CSS3

Let’s add a little bit of interactivity. We’ll make the field that is currently selected expand by adding some padding.

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

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

.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;
}

Step 9: The required Attribute in HTML5

Now 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 before the form can be submitted. Thus, a form cannot be submitted if a required field has not been filled out.

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

<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>

Step 10: Styling required Fields

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

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

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

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

What happens upon submission?

Right now, different browsers will do different things when a form using HTML5 elements is submitted. When the form is submitted, most browsers will prevent the form from being submitted and will display a “hint” to the user, 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:

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

Step 11: Understanding New HTML5 type Attributes and Client-Side Validation

HTML5 validation works according to the type attribute that is set within the form fields. For years HTML only supported a handful of type attributes, such as type="text" but with HTML5 there are a over a dozen new input types 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 the form’s data client-side. If a user’s browser does not support the new type attributes, such as type="email", it will simply default to type="text". This is actually pretty amazing. Essentially you have backwards compatibility in all browsers on earth, hooray!

So what if the browser does actually support the new type attributes? For desktop browsers there is no visual difference (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 iPhone

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


Step 12: Changing the type Attributes

We already have our form fields set to the default type="text". But now we want to change the type attribute on our email and website fields to their corresponding HTML5 type.

<input type="email" name="email" placeholder="john_doe@example.com" required />
<input type="url" name="website" placeholder="http://johndoe.com" required/>

Step 13: HTML5 Validation

As mentioned before, HTML5 validation is based on your type attributes and it is on by default. There is no specific markup required in order to activate form validation. If you wish to turn it off, you can use the novalidate attribute like this:

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

Name Field

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

Now we will create our own CSS to style field inputs that are considered valid and invalid by the browser. If you remember, we used :required in our CSS to style all input elements with a required attribute. Now, we can style 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 in focus. We’ll add a red border, red shadow, and red icon created in photoshop to indicate the invalid field.

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

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

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

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

Email and URL Fields

Our CSS styles and validation rules are already applied to the email field because we set the type and required attributes earlier.


Step 14: Introducing the HTML5 pattern Attribute

Using the type="email" attribute as an example, it appears that most browsers validate that field as *@* (any character + the “@” symbol + any character). This is obviously not very limiting but it does prevent users from entering 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 is any character followed by a colon. So, if you entered “h:” then the field would validate. This is not extremely helpful 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’re going to talk about how to do that in HTML5.

The pattern Attribute

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

<input type="url" name="website" placeholder="http://johndoe.com" required pattern="(http|https)://.+" />

Now our field will only accept values that start with “http://” or “https://” and one additional character. These regular expression patterns can be confusing at first, but once you take the time to learn them, your forms will be open 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.

.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;
}

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

Using the ::before Selector

Now we want to add a little triangle to our hint boxes that help direct and guide the eye. This can be done using images, 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 a small triangle that points left using the ::before pseudo selector. We can do this by using one of the unicode geometric shapes.

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

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

Using the + Adjacent Selector

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

.contact_form input:focus + .form_hint {display: inline;}
.contact_form input:required:valid + .form_hint {background: #28921f;} /* change form hint color when valid */
.contact_form input:required:valid + .form_hint::before {color:#28921f;} /* change form hint arrow color when valid */

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


Step 16: Sit Back and Admire Your Beautiful HTML5 Form

Go ahead and take a look at your final product!


Conclusion

As you can see, the new HTML5 form features are pretty neat! Everything is backwards compatible so incorporating 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 their online forms. However, HTML5 validation still does not replace server-side validation. For the time being, it’s best to use both methods when handling user-submitted information. Thanks for reading!

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

    Whilst I’m all for the use of HTML5 and CSS3 the huge flaw with using the suggested approach is that you would have to replicate this in JavaScript for those IE users… after all we can’t have the form not validating for some users!

    At the moment, I don’t really see the benefit of devoting so much time implementing this within a live project. Conceptually, a great article though.

    • suchetan

      Your tutorial is very Good but not enough to use it. Please apply other form element of this tutorial. Then this tutorial will be more thankful for me and every body who is interested to know this kind of work.

  • Duncan

    Nice tutorial!

    But if I’m right it’s not completely true to say everything is backwards compatible. I’m guessing that when a user with an incompatible browser clicks “submit” everything gets submitted, no matter what is entered.

    • http://jim-nielsen.com Jim
      Author

      When I was referring to backwards compatibility, I was speaking about the new input types in HTML5 (type=email, type=url, etc). Currently the web is filled with millions of forms that ask for your email or website address, and they all use ‘input type=text’.

      But now, HTML5 defines different types like ‘email’ and ‘url’ that you can begin using in your web forms and do browsers crash or freak out for using these new input types? No! Even IE6 doesn’t! Older browsers will simply default to input type=text! New features that are backwards compatible with old software is simply amazing! You can go ahead and use the new HTML input types NOW without worrying about breaking old browsers. Reward users with newer browsers, then maybe the people with old ones will be incentivized to switch :)

      However, as clearly stated in the article, this is no replacement for server side validation :) It’s good to start using these new features now. If they don’t get used, they might not make the spec. YOU as the web designers cast a vote every time you include these new features :) saying “yes, this is a great feature and I want it!”

      • Phil P

        Except for the text-mode browser, w3m, which given an unrecognised type will drop the input element from the web-page, instead of treating it as text.

        For the page I was dealing with, w3m users made up more of the userbase than normal, so I ended up using type=text on the fields and then fixing them up in JavaScript to the HTML5 variants.

  • http://www.snaptin.com Ian Yates

    @George @Duncan – read the tutorial people! As Jim points out, you’d need a server-side validation (or alternatively implemented client-side solution) to back up browsers which don’t support HTML5 validation.

    For browsers which don’t support it, data is validated server side. For browsers which do, the submitted data drifts through the server-side checks without hitch.

    • Duncan

      I’ve read the tutorial and it indeed needs some other kind of validation for full support in all browsers, but since the html5-validation happens client side it would have been nice to see some other form of client-side validation to create one awesome form that works everywhere!

  • http://www.igorapa.com Igor

    I wonder what software is used that has a black background? I’m starting now and am wondering the best tools …

    • http://www.snaptin.com Ian Yates

      Are you talking about the code displayed in the tutorial?

      • http://igorapa.com Igor

        Yes .. I just use Dreamweaver to code, I want to know what software you are using for this tutorial because the background is black

        • http://martinansty.co.uk Martin Ansty

          They aren’t screenshots… they’re just text that has been nicely formatted in a similar way to how most code editors present code (try selecting the text)

          • http://www.igorapa.com Igor

            I already know … I just want to know the name of the software has the function to let the black background to better plan the night, or Dreamweaver can do that?

        • Avery

          Igor, my personal recommendations would be PSPad and Sublime Text 2, both of which have customizable color interfaces :D

          I like my PSPad color setup so much I wrote it down for use in other places.

          • http://www.igorapa.com Igor

            Hello Avery, thank you for the information … I live in Brazil, and although the country is increasing, yet I see difficulties in technology, in short, programming and structures … I love it and try to learn English with blogging, but do not quite understand the language, so I’m struggling to learn in the race … Anything you indicate to me I follow, I thank you!

        • zeonos

          I use eclipse (google the php version), where you can customize your colors.
          you can even share them ( http://eclipsecolorthemes.org/ )

  • http://flashjourney.com/ Mahfoodh

    Nice article … I need to put more time to start learning the new cool features of HTML5 and CSS3.

  • Carlos

    Yup… Actually, server-side validation is a must even if you have any type of client-side validation, so yeah, no problem there. Nice article!

  • http://home.iitb.ac.in/~amol_mandhane/ Amol Mandhane

    Server side validation is a must. Whatever you are using on client side, you cant neglect server side validation. The purpose of HTML5 validation is to improve user experience and spot the input errors quickly for the people who use advanced browsers.

  • http://www.josephvillajin.com Joseph Villajin

    Great Article! Unfortunately this isn’t widely supported, it is great to see what html5 and css3 can do.

  • Scott

    Great form – but it doesn’t seem to work at all in IE9. I’m just learning HTML5 / CSS3. Saw your one minor disclaimer on IE9, but shouldn’t it at aleast work without the placeholder text?

  • Pingback: Bring Your Forms Up to Date With CSS3 and HTML5 Validation | Shadowtek | Hosting and Design Solutions

  • Pingback: Online Articles and Tutorials

  • Mark

    Been using this for a while and combined with Modernizr we detect whether the browser supports HTML5 validation. If not we fall back to JavaScript and everything is still validated server side.

    By the way, you can also target

    ::-webkit-validation-bubble-arrow

    and

    ::-webkit-validation-bubble-message

    The only problem I sometimes have though is that they position weirdly in relation to the form elements. It all depends on how the form elements are positioned on the page!

    • http://Jim-Nielsen.com Jim
      Author

      Thanks for the tips Mark. The validation bubbles are pretty different across browsers. Hopefully this is something that will become more standardized in the future

  • http://lukespoor.com Luke Spoor

    If this is using HTML5, why did you use for the email input? We can use ;-)

    • http://www.snaptin.com Ian Yates

      Oops, something lost in translation there Luke – I’m not sure what you think should have been used instead of input type=email?

  • http://www.konceptweb.co.uk Manos

    Excellent tutorial. That’s all I have to say.People should thank you for teaching these stuff :)

  • Shiro

    -webkit-border-radius: 3px;
    -moz-border-radius: 3px;
    -ms-border-radius: 3px;
    -o-border-radius: 3px;

    arg… why the w3c / browers just standardize this..
    border-radius: 3px;
    That will make web developers life more easy. Just detect the syntax, then they do their own engine conversion at the back. What so difficult….Zzzzz

    Maybe next time someone write an engine to do the convert before publish to the web.

  • Vinicius
    • http://jim-nielsen.com Jim
      Author

      Vinicius, by posting that link I’m assuming you are pointing out my character error? I just realized I used the HTML HEX code on the first geometric triangle, but then used Dec notation for the others. Sorry! The link you provided is a good reference if you need to use those characters. Thanks!

  • http://titan-creative.net S3bY

    Nice post, Jim! I like your workflow!

  • http://alexklimok.com Alex

    Good post, but as with many form styling posts, checkbox and radio button validation is not included. Can you please focus on those as well? If this isn’t possible with HTML5, then please address this issue and include a workaround (jquery).

    Thanks again, good post!

  • http://smartenough.org DNABeast

    I’ve sometimes found using definition lists rather than unordered lists very useful in semantically presenting this sort of information. What are your thoughts on this?

  • http://www.wimbledon-it.co.uk bpr

    Nice article. I really like it and like the CSS for the required field. I didnt know that we can use :valid for instance. Thats very useful. I fully support HTML5 and CSS3.

    And I dont understand why people actually argue about having server side validation…. YOU ALWAYS NEED server side validation. There is only one case where you dont need it and thats if you are validating your own input in a static page on localhost :P but as soon as your works leaves your localhost and other people are involved you cannot trust anybody! So get over the server side validation topic there is nothing to discuss.

    Anyways. Appreciated article! Keep it up.

  • Pingback: HTML 5 validations | SeekPHP.com

  • http://www.amaresh.com.np Amaresh

    Good post, I like it very much bcoz. I was in need of it
    Thanks once again for the post

  • http://eamdevelopers.com Joseph

    This helped me a lot. Thanks

  • Gary

    Hi Jim, Great article. There was lots of new stuff in here I wasn’t aware of.

    I was trying it out and wondered if you had any suggestions on how to style a field which was not a required input, but should still display the valid style format when data had been entered in it.

    I tried .contact_form input:valid which technically works because it always shows as valid but the behaviour I’m looking for would be the normal style and then the valid style only once something has been entered.

    • http://jim-nielsen.com Jim
      Author

      Hm…that’s an interesting question…if I understand it correctly. The only way I can think to do that would be using javascript…since you’re not using the browsers built-in HTML5 capabilities with detecting the information entered in the form, you’d have to use javascript to detect when some kind of value has been entered in the form (then simply add/remove a class name to the input field).

      There may be another way…but that’s the only one that comes to mind off the top of my head.

  • http://beben-koben.blogspot.com/ Beben Koben

    so cool ♥ ☺

  • http://PSDtutorials.co.uk Peter Sawyer

    Love the tutorial and end outcome, however one question.

    I have added a phone number field and I cannot seem to get the correct regular expression so it only excepts numbers. Any pointers?

    I am using Gen validator JS as well so its not massively important… as it will not allow spam through…. it would just be nice on a visual level.

    • http://jim-nielsen.com Jim
      Author

      Peter, this might be a resource that will come in handy for you: http://html5pattern.com/

  • Ben

    Does anyone know where I can find a jQuery version of this really cool required character check for the password field like Apple does?

    https://appleid.apple.com/cgi-bin/WebObjects/MyAppleId.woa/wa/createAppleId?localang=en_US

    Any help would be great.
    Thanks!

  • http://www.tips4design.com Cristy

    The validation rules aren’t that good, you can enter “m@m” for e-mail, http://…………google.com for website, etc…

  • http://allthingswebdesign.com Tom

    Frickin awesome tutorial. I didn’t know it was possible to not use any javascript/jQuery to achieve all the sweet little effects you’ve showed us. HTML5 validation = Awesomeness. This tutorial = Sweet mama loving awesomeness!!

  • thethe lwin

    Great !

  • Leo

    This was an excellent step by step tutorial. I learned heaps following it through. I and I also learned that you guys in America don’t use the word “learnt”. Two birds in one shot, simply amazing! Thanks for sharing the knowledge.

  • Leo

    This was an excellent step by step tutorial. I learned heaps following it through. I also learned that you guys in America don’t use the word “learnt”. Two birds in one shot, simply amazing! Thanks for sharing the knowledge.

  • Heber

    If I put “example@example” in the email field, it will validate. Don’t forget to check that the email has a valid extension, otherwise this would result into corrupt data on your forms. Splendid article though :)

  • Pingback: Best of Tuts+ in November | Graphfucker

  • Pingback: Best of Tuts+ in November | Flash Video Traning Source

  • Pingback: Best of Tuts+ in November 2011 | Omega Pixels

  • Pingback: Best of Tuts+ in November 2011 - Tutorial Finder

  • Pingback: Best of Tuts+ in November | Webdesigntuts+

  • Pingback: Best of Tuts+ in November 2011 | clickshots

  • Pingback: Best of Tuts+ in November 2011 | CS5 Design

  • Pingback: Best of Tuts+ in November | Shadowtek | Hosting and Design Solutions

  • Pingback: Best of Tuts+ in November 2011 | Shadowtek | Hosting and Design Solutions

  • Pingback: Best of Tuts+ in November 2011 | Graphfucker

  • Pingback: Best of Tuts+ in November | clickshots

  • Pingback: Best of Tuts+ in November | Wptuts+

  • Pingback: My Stream » Best of Tuts+ in November

  • Pingback: Best of Tuts+ in November 2011 | Inspirations, dreams, humaniora

  • Pingback: Best of Tuts+ in November | linuxin.ro

  • Pingback: Best of Tuts+ in November | Freelancing Help

  • Pingback: Best of Tuts+ in November – blog

  • Pingback: Best of Tuts+ in November « Fast Ninja Blog by Freelanceful – Web Design | Coding | Freelancing

  • Pingback: Best of Tuts+ in November « CSS Tips

  • Pingback: Best of Tuts+ in November : Ahmad Assaf`s Blog

  • adnan

    How do I add checkboxes with HTML 5 that go with the design given above

  • Pingback: Best of Tuts+ in November « Fernando Polania

  • Pingback: Best of Tuts+ in November 2011 « Fast Ninja Blog by Freelanceful – Web Design | Coding | Freelancing

  • http://jaywilsonjr.com/blog Jay Wilson Jr.

    EXCELLENT tut!

    Thank you for taking the time to write this up. It would be awesome if you found the time to post a video to go along with the tut. Thanks again mate!!

    Great job!

    Jay

  • Jonathan Fontes

    Hello,

    I saw in the screenshot that you use and app of mac for see the result of html, right ?! I can give me the name please, only for curiosity.

    The Best,
    Jonathan

  • Pingback: Liens du _ _ [No. 29] « blog.simonlegare.com

  • Pingback: Best of Tuts+ in November - InterlaceLab

  • Iman

    Thanks, I was waiting for it.

  • Pingback: Best of Tuts+ in November | Pro Sound Central

  • Henry

    Awesome tutorial !! This is what I wanted to find

  • Pingback: Best of Tuts+ in November | Think And Design : Jordan webdesign and e-marketing

  • http://www.designforce.us Hafeez Ansari

    Great tutorial. Please keep it up!. Thank you for this nice sharing.

  • http://google.com Fercho

    Hola muy buen trabajo, pero tengo una pregunta, en la parte de las fonts me trabo porque pide la url de las fonts me gustaria saber que hago en esa parte. hay hostings de fonts? o que pongo ahi esa es mi pregunta . Gracias

    PD: soy de argentina estoy usando el traductor de google si falla perdon. Bye

  • thomas

    EXPECTACULAR tu tutorial muchas gracias me servirá de muchísimo lejos la mejor validación que e visto en mi vida

  • //willfris.nl/ immeëmosol

    remark:

    the text that explains the meaning of the asterisk is not unobtrusive.

    Because: what if i can’t see the image that is used?

    suggestion 1 , remove text in html and change :
    .required_notification {
    color:#d45252;
    margin:5px 0 0 0;
    display:inline;
    float:right;
    }
    into :
    .contact_form h2::after {
    content: ‘* Denotes required field.’;
    color:#d45252;
    margin:5px 0 0 0;
    display:inline;
    float:right;
    }

    suggestion 2 :
    at the asterisks in the html and hide them with css.

  • Ds Save

    Great job!

  • Big Boss

    Nice tut, But why don’t people ever provide the PHP side of a form.

    A form is useless without the PHP to send the data. It’s like offering someone a car without any wheels.

  • Pingback: Web Design and Development News - 12/16/2011 | Webmodulite Demo Blog

  • Tony

    Hello,
    Any help on drop downs and making them the same style?

    Thanks,
    Tony

  • Helena

    wow..the best tutorials are here… thanks vewy much!

  • Pingback: Tutorials #23 | skyINX

  • Pingback: Quickly Build a Swish Teaser Page With CSS3 | Webdesigntuts+

  • Pingback: Quickly Build a Swish Teaser Page With CSS3 |

  • Pingback: Quickly Build a Swish Teaser Page With CSS3 | Shadowtek Hosting and Design Solutions

  • Pingback: Quickly Build a Swish Teaser Page With CSS3 | How to Web

  • Pingback: Bring Your Forms Up to Date With CSS3 and HTML5 Validation : DevMI

  • Steven

    I love this! Thanks Jim. Now, I know the power of HTML5.

  • Pingback: CSS3HTML5 » Learn HTML5: HTML5 Tutorials and Guides

  • Pingback: Создайте с помощью CSS3 страницу с роскошным тизером-приманкой.

  • Rick

    Thanks for a great tutorial. I used this for a web site I am creating for my business. I’m not a designer but over the last six months I have learned a lot just searching for tutorials and reading comments for problems people were having in their designs.
    I have a page with two forms on it, one of which has a dropdown box. I never could get the dropdown box to look exactly like the others, but it works without obscuring the state. I’ll keep working until I figure it out

    And now I understand why so many people dis Internet Explorer. Everything works well in Opera, Safari, Firefox and Chrome. In Internet Explorer you only see a portion of the code functioning.

  • zeonos

    The demo seems to be a bit off with the validation.

    zzz@zzz is a valid email?
    http://www.something.com is not a valid website. (who really puts http://something.com as their mail?.

  • Gabe

    Hey Jim.

    Thanks for the fantastic tutorial. I’ve been looking for some good tutorials on web form – mostly the best solutions for marking up the code ie: using a tables, using definition lists and so on.

    In any case, I wanted to ask you why you used display:inline and display:inline-block on .required_notification, .contact_form label and the h2?

    When removing those three display properties and adding the following I get the same visual result.

    .contact_form li:first-child {overflow: hidden;}

    Could you please explain? I normally just use either a float or an inline display, not really both ever together… So I’m just trying to understand why and when I should be using both together.

    Any information would be greatly appreciated. Thanks!

  • Uri

    Really nice tut ! Gratz Jim.

    But I’m having a code problem with the CSS (I think it is). I’m sure it’s a stupid error but I don’t have the enough expe to solve it by myself.

    The prob is when you click on an input text and it expands with the CSS I just can’t see what the input contained before. Ex: In the name case, first you can read “John Doe”, in my case, when I decide to write a name i just can’t see it until it’s done and another input is clicked (like you’re done with the name and you decide to complete the email). On the other hand, when I click that input (still in the name case) but I decide not to write yet I click for ex on the email input and with that action now I can read “joh” of “John Doe” while im on the email input.

    Is that a browser prob?Because I make some tests with Chrome, Safari, Firefox and Iron.

    I’ve copied the entire code and understand the most part and play with it.

    Gratz again for that tut Jim.

    Uri.

  • Pingback: Bring Your Forms Up to Date With CSS3 and HTML5 Validation | Webdesigntuts+ » Web Design

  • Boris

    Hi,

    Nice contact form, although it seems that I can’t translate everything. Some error messages are still in English and I was not able to find them in css or html file.

    Kind regards

  • http://sparque.me Sebastian

    Great tut, and congrats. I have a UX issue with the form though. The user should not immediately see an “invalid” form error when they first click the input. It’s as if they’ve already messed something up before typing.

    A delay could be used here, or the form could be validated on blur (focusOut)

  • joe

    Doesn’t work in IE

    • http://twitter.com/occtopia Jason Occhipinti

      LOL…what else is new, right?

    • http://www.facebook.com/ProfessionalASPNET Chris Love

      it works just fine in IE

    • http://www.facebook.com/profile.php?id=637130550 Neil Burleigh

      The required atribute is not supported in IE 9 and below, but then again what else is….

  • http://www.lwwcm.com Pete

    Interesting to note that the type=”email” will incorrectly validate “joe@bloggs” as being valid. There is obviously still a LONG way to go before HTML 5 is released as a working standard.

    • Norbert Melzer

      You are wrong! joe@bloggs IS indeed a valid email-address! I use one of that kind everyday in my LAN.

    • Ian Simmons

      I think it’s because it needs the pattern attribute regex to actually require .com, .net, etc. Same for the url. The example code pattern for the url is only checking for http|https followed by anything.

  • Pingback: Styling HTML5 Forms with New CSS3 Pseudo-classes | Tutorials

  • balu

    Nice Tutorial
    But validation not completed ,,give me validation for mobile number using html5

  • Pingback: Get Your Form On: Modern Web Forms Tutorials | TuTsRUS - All Adobe Tutorials - Photoshop | Illustrator | Encore | Premeire | After Effects

  • Pingback: Advertisement

  • Pingback: FROM: www.internet-cart.com | Get Your Form On: Modern Web Forms Tutorials

  • Pingback: Website Design | Get Your Form On: Modern Web Forms Tutorials

  • Pingback: Get Your Form On: Modern Web Forms Tutorials | Sacima Appress

  • http://blog.hizup.com Rixo

    Very good tutorial!

  • Pingback: HTML5/CSS3 Tutorials that can Inspire Designers and Developers | xhtml spruce

  • Malik

    Hi

    Thanks for the tutorial.
    You should take care of your unicode geometric shapes code, only the first is written in HTML Hex, the others are in Decimal, check this : http://en.wikipedia.org/wiki/Geometric_Shapes.

  • Pingback: Modern Web Forms Tutorials Collection - IT News | IT News

  • sam

    you made my day.. actually mornning..
    i have been coding for form validation in jquery and that literally took a large bunch of time and i was stuck with the preventDefault..

    Thank you very much Sir… You have nice Day !!

  • Norbert Melzer

    input:required is no valid CSS, perhaps you should use input[required] or a similar construction to achieve your goal.

  • Steve

    Looks great, just wondering why there is no validation when viewed on ipad?
    You can click “submit form” anytime and it goes through

    • http://www.facebook.com/profile.php?id=637130550 Neil Burleigh

      The required atribute is not supported in safari according to w3schools.

  • http://www.facebook.com/ejita.karim Ejaz Karim

    nice tutorial :)

  • Pingback: 28 Best Collection of Useful CSS3 Effects with Tutorials - BlueInfoBox

  • chris

    Although I like your workflow and love the end result, I feel you should perhaps provide a fallback example for older browsers, maybe using jQuery, because although your example works; it couldn’t be used in a production environment without someway of gracefully degrading the experience.

  • maksa

    very informative post .. :-)

  • maksa

    nice tutorial..for validation

  • Chris

    Nice tutorial! Though, in my opinion, when the user focuses on a form element shouldn’t be show as an error (red and exclamation sign) but more as a neutral/informational tooltip, because the user haven’t made a mistake yet by just focusing the element. Only after the validation (live or at submit) has failed (means that the user made a mistake), the error style could be displayed.

    • Michael Brent

      You’re right, displaying after lose the focus is another solution (but I think will need some javascript help)

      • Chris

        Could be an option, why not? But, I think that the user’s experience comes first and the implementation second. That’s why, in my opinion, for a nice form implementation you might want to mix live validation (e.g. emails, passwords, etc.) with validation at submit, with CSS3 and few Javascript (where it’s needed, CSS3 comming first).

        But this is not the mission of this post, which treats some nice stuff that can be done using just CSS3 and no Javascript at all, and even if the tutorial has this small UX issue, definetly it can be usefull.

  • Pingback: Bring Your Forms Up to Date With CSS3 and HTML5 Validation | Webdesigntuts+ | Important Links

  • Derrick Lambert

    The regular expressions need some work but other than that great tutorial

  • kuzvac

    What is “-ms-border-radius”? IE<9 doesn't support css3 property border-radius and doesn't support ms-border-radius property. Don't confuse people :)

    • Gabriel

      border-radius and box-shadow doesn’t need vendor prefixes anymore

  • Pingback: HTML5とCSS3でメールフォームのValidationと入力ヒント スタイルシートマニア ホームページ制作ならソースマリン

  • Tim

    Thank you! Nice tutorial.
    But it doesn’t work with IE, right? somebody here, who get this work on IE ?

    • http://www.facebook.com/profile.php?id=637130550 Neil Burleigh

      The required atribute is not supported in IE 9 and below

  • http://ivatanackovic.com Iva

    It’s “your” forms, not “you’re” forms. Other than that, thank you so much. Was looking for a collection of all these in one place. :) Happy New Year!

    • ianyates

      Well spotted (why had no-one else pointed that out?!) Edited, thanks :)

      • http://www.facebook.com/profile.php?id=1311520144 Steini Pé

        Also in the text you write “greed icon” instead of “green icon” but this is just small typos :) beautiful tutorial

        • http://ivatanackovic.com Iva

          You’re welcome. And greed icon…that could be an idea for an inspiring story. I like the combination of words…

  • Guest

    Very nice, I have already implemented most of the new features on my website. Here is a pattern attribute for validating email address: pattern=”^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,6}$”

    • Kumar A

      That was excellent little snippet. I was looking for something just like that. Thanks a ton

  • Arvind Mehra

    Nice tutorial man….
    From where do you learn this stuff if you have some occult site or book or blog pls do tell me dude.
    I like this kind of pretty stuff

  • Oleg K

    Great tutorial.
    I think it’s a good practice to use HTML5 validation where possible, as it’s fast, but still allow other types of client-side validation (like jquery form validation e.g.) for the users with older browsers.

  • http://www.facebook.com/marcin.domanski1 Marcin Domański

    A have one question. Why you create form fields in UL list? Is it semantic good?

  • Pingback: 教程:让你的表单升级到CSS3和HTML5验证 | 觉唯前端

  • ianyates

    Jim does briefly talk about context-aware characters – there’s definitely a lot of UX potential where using the right element for the job is concerned :)

  • John

    The form isn’t valid markup. You can’t wrap block level tags (h2 element) inside inline tags (li).

    • Stephen

      LI tags Are block level, and can contain absolutely any valid HTML tag.

  • Todd

    I don’t dig the red loud fields before input either.

  • Pingback: Tasarımcılar için 35 HTML5 ve CSS3 Öğretici Kaynak ~ iWebTunes

  • David

    Nice tutorial! Html5 and CSS3 are best :)

  • Pingback: Сделайте современные формы с помощью CSS3 и валидации HTML5. | BomBear

  • Pingback: 10+ Fresh CSS3-Only Tutorials (Look Ma, No Javascript!) | gonzoblog

  • @ruizfrontend

    I can’t understand why there’s no form::valid or form::invalid rules. When there are some invalid input It would make really easy to style a disabled submit button with form::invalid input[type=submit]

  • http://www.facebook.com/marcela.flores.904108 Marcela Flores

    Thank you! love the validation with html5 and css3.

  • Mehmet

    this is awesome , thanks

  • Matt

    I’m using your form, but is there any way to make it more compatible on IE? Required is not working.

  • http://www.facebook.com/ismarlonassuncao Marlon Assunção

    Great job!

  • Sylwevrin

    Is it possible to get it to send the info to an email address? And if so, how do I do that

  • Pingback: Good Contact Form | PHPsolutionBD

  • Pingback: Designing a Better Contact Page | Webdesigntuts+

  • xzed

    Don’t want to be a smart-ass,
    but I’ve found a common mistake in there,
    which you can see in lots of forms in the web:
    (and now generations of becoming web-designers may have learned it false ;) )

    The “for” attribute of a has to be the “id” of the related input
    not the “name” !

    (You don’t need a “for” attribute if the input is wrapped by the label)

    You can easily see the difference by taking a look at their demo page:
    Click on a label and nothing will happen,
    because the browser has no clue to which element the label belongs.
    So edit one input with the browser’s dev tool giving it the missing “id” attribute and
    click the label again.
    The input will be focused, as soon as you click the label.

  • Pingback: Designing a Better Contact Page - — Ethiopian Website Design

  • Pingback: 役立つこと間違いなし!フォーム用フリーテンプレート50+ | yugurido

  • http://www.danawebdesign.com/ longbeachwebdesign

    I am currently working on an HTML5 form and using CSS3 for the styling.
    but its the CSS below that for some reason is not working.

    input:valid.fields, textarea:required:valid.fields, select:value.fields
    {
    background:url(“images/tick.png”);
    background-position: right;
    width: 200px;
    background-color: white;
    opacity: 1.0;
    }

    long beach web design