Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML5

CSS: Custom HTML5 Form Validation with Visual Effects using Pseudo Class

4.94/5 (9 votes)
7 Oct 2014CPOL1 min read 9K  
CSS: Custom HTML5 Form Validation with Visual Effects using Pseudo Class

Introduction

As we know, Pseudo Code is an informal descriptive language which helps human beings to understand the code, rather than just only machine readable. CSS pseudo-classes are used to make the UI more interactive and user-friendly, that means to add special effects to some CSS selectors.

The syntax of pseudo-classes is as follows:

HTML
selector:pseudo-class {
    property:value;
}

Let’s check an example how :valid and :invalid pseudo-classes work.

HTML
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <style type="text/css">
	    input:required:invalid, input:focus:invalid { 
		background: url(https://pravasini.files.wordpress.com/2014/09/invalid1.png) no-repeat right top;
	    } 
		
	    input:required:valid { 
		background: url(https://pravasini.files.wordpress.com/2014/09/valid.png) no-repeat right top; 
	    } 
	</style>
    </head>
    <body>
	<form action="" method="post">
	    <label for="email">Email: </label>
	    <input type="email" required>
	    <button type="submit">Go </button>
	</form>
    </body>
</html>

The above code will output as:

invalid

OMG!! 8-O without adding a single line of JavaScript code, how are we able to show customize error icon :-|.

WOW!! Great :) … That’s really cool 8-). We added CSS for focus invalid input, that’s why it is showing the invalid input icon.

Check the below output on valid URL input:

invalid

There are a lot more Pseudo Class available through which we can really add special effects without using JavaScript. Below listed Pseudo Classes are some of the examples among those:

  1. :first-child
  2. :focus
  3. :hover
  4. :right
  5. :target
  6. :valid
  7. :visited
  8. :active
  9. :checked
  10. :default
  11. :dir()
  12. :disabled
  13. :empty
  1. :enabled
  2. :first
  3. :root
  4. :scope
  5. :last-child
  6. :last-of-type
  7. :left
  8. :link
  9. :not()
  10. :nth-child()
  11. :only-child
  12. :first-of-type
  13. :fullscreen
  1. :only-of-type
  2. :optional
  3. :out-of-range
  4. :read-only
  5. :read-write
  6. :required
  7. :indeterminate
  8. :in-range
  9. :invalid
  10. :lang()
  11. :nth-last-child()
  12. :nth-last-of-type()
  13. :nth-of-type()

Note: Please check here for browser support details.

Thanks :) and I will be happy to head from you.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)