« Best. Cardboard. Star Wars. Fan movie. Ever. | Main | RIA Unleashed: Boston is a great time »

New HTML5 pseudoclasses for form inputs

I just learned about some great new pseudoclasses in HTML5 for use on input tags: :valid and :invalid (These are among the many other new features in CSS3). Used in conjunction with the new validation capabilities for input fields, you can write styles which will change the appearance of your inputs in real time depending on where the cursor is in the form and what data the user has entered.

The new validation capabilities of HTML5 have to do with the new input types: "email", "url", "number", or "date", and the new "required" attribute. These new types are supported by most browsers except for Firefox, and just appear as regular text inputs in non-compliant browsers (and the "required" attribute will just be ignored). For example, in HTML5 you can now create a field like this:

Email address: <input type="email" name="your_email" required="true" />

Using these new features allows the use of the new pseudoclasses:

  1. When your input field has the "required" attribute set, it will match the pseudoclass :valid if it has a value entered (unless the value doesn't match an additional validation rule)
  2. If your input field has the "required" attribute set and it does not have a value entered, it will match the :invalid pseudoclass.
  3. When your field is of type "email", "url", "number", or "date", and the value entered is not of the corresponding type, the will input will match the pseudoclass :invalid.

So our CSS can look like this (only works in Chrome, Safari, and Opera):

<style>
input:valid { border: 1px solid green; }
input:invalid { border: 1px solid red; }
</style>

<form>
Your name: <input type="text" name="your_name" required="true" /><br />
Email address: <input type="email" name="your_email" required="true" />
</form>

Give it a try:

Your name: Required
Email address: Valid email required

Better yet, you can use the "adjacent" selector to style messages next to your inputs (only works in Chrome, Safari, and Opera):

<style>
input:valid + span { color: green; }
input:invalid + span { color: red; }
</style>

<form>
Your name: <input type="text" name="your_name" required="true" /><br />
Email address: <input type="email" name="your_email" required="true" />
</form>

Give it a try:

Your name: Required
Email address: Valid email required

Comments (2)

ense to the student.

As a photo editor you will be given the task of correcting or modifying
an image. The power of personal recommendations
should not be overlooked. Resumes created from a
template are commonly used by individuals that need a simple, professional resume quickly; however, they are typically more ordinary than a resume created without a template.

Post a comment


Type the characters you see in the picture above.