HTML5 Form Validation Example

Since the initial time of web designing, we have been in compulsion to validate our form in terms of preventing spammers or for getting appropriate input from users.

Before the development of HTML5 we were using the JavaScript or the other Back End language to validate our form. But the HTML5 has changed the entire things in programming technology. For validating a form a library (H5F) has been introduced to giving better performance with HTML5.

In this tutorial will learn how you can validate your form with HTML5 ?. Either you can see the demo and download the source code or can go through our tutorial, which will demonstrate the scripts with example to understand it better.

Download

Demo

How I created this stylish form that is fully validated with HTML5 ?

This form has been made with CSS3, HTML5 and H5F JavaScript library. Please follow the steps to learn this validation.

1. Input Text Field Validation

Input Text Field Validation


 <fieldset>
  <legend>Input Text Field Validation</legend>
  <ol>
   <li>
    <label for="firstname">First Name *</label> 
    <input type="text" id="firstname" name="firstname" placeholder="First Name" required />
   </li>
   <li>
    <label for="lastname">Last Name *</label> 
    <input type="text" id="lastname" name="lastname" placeholder="Last Name" required />
   </li>
  </ol>
 </fieldset>
 <input type="submit" value="Sign up" />

Download


2. Email and URL Validation

Email and URL Validation
  1. Please enter a valid email address e.g. swapnil@example.com
    Your email address is now valid

  2. Please enter a valid URL address e.g. http://www.html5andcss3.org
    Your URL address is now valid


 <fieldset>
  <legend>Email and URL Validation</legend>
  <ol>
   <li>
    <label for="email">Email *</label> 
    <input type="email" id="email" name="email" placeholder="e.g. swapnil@example.com" title="Please enter a valid email" required />
    <p class="validation01">
     <span class="invalid">Please enter a valid email address e.g. swapnil@example.com</span>
     <span class="valid">Your email address is now valid</span>
    </p>
   </li>
   <li>
    <label for="url">Website *</label> 
    <input type="url" name="url" id="url" placeholder="e.g. http://www.html5andcss3.org" title="Please enter a valid URL" required />
    <p class="validation01">
     <span class="invalid">Please enter a valid URL address e.g. http://www.html5andcss3.org</span>
     <span class="valid">Your URL address is now valid</span>
    </p>
   </li>
  </ol>
 </fieldset>
 <input type="submit" value="Sign up" />

Download


3. Mobile or Phone Number Validation

Mobile or Phone Number Validation
  1. No spaces or brackets e.g. 9999999999
    Your mobile number is valid


  <fieldset>
   <legend>Mobile or Phone Number Validation</legend>
   <ol>
    <li>
     <label for="tel">Mobile *</label> 
     <input type="tel" id="tel" name="tel" pattern="d{10}" placeholder="Please enter a ten digit phone number" required />
     <p class="validation01">
      <span class="invalid">No spaces or brackets e.g. 9999999999</span>
      <span class="valid">Your mobile number is valid</span>
     </p>
    </li>
   </ol>
  </fieldset>
<input type="submit" value="Sign up" />

Download


4. Drop Down Box Validation

Drop Down Box Validation


  <fieldset>
   <legend>Drop Down Box Validation</legend>
   <ol>
    <li>
     <label for="state">Country</label>
     <select name="state" id="state">
      <option>Africa</option>
      <option>America</option>
      <option>Australia</option>
      <option>China</option>
      <option>England</option>
      <option>Japan</option>
      <option selected>India</option>
      <option>Indonesia</option>
     </select>
    </li>
   </ol>
  </fieldset>
<input type="submit" value="Sign up" />

Download


5. Number Validation With Specific Range

Number Validation With Specific Range
  1. Your postcode is out of range between 10001 – 999999
    Your postcode is in the correct range


  <fieldset>
   <legend>Number Validation With Specific Range</legend>
   <ol>		   
    <li>
     <label for="postcode">Post code *</label>
     <input id="postcode" name="postcode" type="number" min="10001" max="999999" maxlength="6" required />
     <p class="validation01">
      <span class="invalid">Your postcode is out of range between 10001 - 999999</span>
       <span class="valid">Your postcode is in the correct range</span>
     </p>
    </li>
   </ol>
  </fieldset>
<input type="submit" value="Sign up" />

Download


6. Textarea Validation

Textarea Validation


  <fieldset>
   <legend>Textarea Validation</legend>
   <ol>		   			
    <li>
     <label for="address">Address *</label>
     <textarea id="address" name="address" type="text" required></textarea>
    </li>
   </ol>
  </fieldset>
<input type="submit" value="Sign up" />

Download


7. CheckBox and Radio Button Validation

CheckBox and Radio Button Validation
  1. Male Female


  <fieldset>
   <legend>CheckBox and Radio Button Validation</legend>
   <ol>		
    <li>
     <label for="username">Agree to T & C *</label>
     <input id="checkbox" name="checkbox" type="checkbox" required />
    </li>
    <li>
     <label for="username">General *</label>
     <input id="radio" name="radio" type="radio" required />Male <input id="radio" name="radio" type="radio" required />Female
    </li>				
   </ol>
  </fieldset>
<input type="submit" value="Sign up" />

Download


8. Password Validation Using Pattern

Password Validation Using Pattern
  1. Minimum 8 characters, one number, one uppercase letter and one lowercase letter
    Your password meets our requirements, thank you.


  <fieldset>
   <legend>Password Validation Using Pattern</legend>
   <ol>						
    <li>
     <label for="password">Password *</label>
     <input id="password" name="password" type="password" title="Minimum 8 characters, one number, one uppercase and one lowercase letter" pattern="(?=^.{8,}$)((?=.*d)|(?=.*W+))(?![.n])(?=.*[A-Z])(?=.*[a-z]).*" required /> 
     <p class="validation01">
      <span class="invalid">Minimum 8 characters, one number, one uppercase letter and one lowercase letter</span>
      <span class="valid">Your password meets our requirements, thank you.</span>
     </p>
    </li>
   </ol>
  </fieldset>
<input type="submit" value="Sign up" />

Download


Now for giving some style to your form you can use this CSS, which will represent your form in an innovative way.

CSS for HTML5 form

body, form, ul, li, p, h2, h3, h4, h5
	{
	margin: 0;
	padding: 0;
	}

body 
	{
	background-color: #ffffff;
	color: #666;
	}

#signup img 
	{
	border: none;
	}

#signup p
	{
	margin: 0 0 1em 0;
	}

#signup h2 
	{
	font-size: 14px;
	margin: 0 0 12px;
	}

#signup
	{
	margin: 20px auto;
	width: 500px;
	}

#signup fieldset
	{
	margin: 0 0 20px;
	padding: 20px;
	-webkit-border-radius: 5px;
	-moz-border-radius: 5px;
	border-radius: 5px;
	}

#signup ol
	{
	list-style-type: none;
	padding: 0;
	margin: 0;
	}

#signup li
	{
	margin: 0 0 12px;
	position: relative;
	}

#signup label
	{
	width: 150px;
	display: inline-block;
	vertical-align: top;
	}

legend
	{
	color:#00C492;
	}

#signup fieldset input,#signup fieldset select
	{
	background: #fff url(ico_validation.png) 260px 24px no-repeat;
	display: inline-block;
	width: 250px;
	border: 1px solid #00C492;
	padding: 3px 26px 3px 3px;
	-moz-transition: background-color 1s ease;
	-webkit-transition: background-color 1s ease;
	-o-transition: background-color 1s ease;
	transition: background-color 1s ease;
	-webkit-border-radius: 5px;
	-moz-border-radius: 5px;
	border-radius: 5px;
	}

#signup fieldset textarea
	{
	display: inline-block;
	width: 250px;
	border: 1px solid #00C492;
	padding: 3px 26px 3px 3px;
	-moz-transition: background-color 1s ease;
	-webkit-transition: background-color 1s ease;
	-o-transition: background-color 1s ease;
	transition: background-color 1s ease;
	-webkit-border-radius: 5px;
	-moz-border-radius: 5px;
	border-radius: 5px;
	resize:none;
	}

#signup fieldset input[type="checkbox"]
	{
	width:20px;
	}

#signup fieldset input[type="radio"]
	{
	width:20px;
	}

#signup fieldset select
	{
	width: 280px;
	padding: 3px;
	}

#signup fieldset #postcode
	{
	padding: 3px;
	width: 270px;
	}

#signup input::-webkit-input-placeholder,#signup input:-moz-placeholder input:placeholder
	{
	color: #f2f2f2;
	}

#signup .validation01
	{
	background: #F08080;
	color: #fff;
	display: none;
	font-size: 12px;
	padding: 3px;
	position: absolute;
	right: -160px;
	text-align: center;
	top: 0;
	width: 150px;
	outline: 0;
	-moz-box-shadow: 0px 0px 4px #ffffff;
	-webkit-box-shadow: 0px 0px 4px #ffffff;
	box-shadow: 0px 0px 4px #ffffff;
	-webkit-border-radius: 5px;
	-moz-border-radius: 5px;
	border-radius: 5px;
	}

#signup input:focus + .validation01
	{
	display: block;
	}

#signup input:focus:required:invalid + .validation01 .valid,#signup input.error:focus + .validation01 .valid,#signup input.required:focus + .validation01 .valid,#signup input:focus + .validation01 .valid
	{
	display: none;
	}

#signup input:focus:required:valid + .validation01,#signup input.valid:focus + .validation01
	{
	background: green;
	}

#signup input:focus:required:valid + .validation01 .invalid,#signup input.valid:focus + .validation01 .invalid
	{
	display: none;
	}

#signup input:focus:required:valid + .validation01 .valid,#signup input.valid:focus + .validation01 .valid
	{
	display: block;
	}

#signup fieldset input:required:valid
	{
	background-color: #fff;
	background-position: 260px -61px;
	}

#signup input.error
	{
	background-color: #F08080;
	background-position: 260px 3px;
	outline: none;
	}

#signup input.required
	{
	background-color: #fff;
	background-position: 260px -30px;
	}

#signup input.valid 
	{
	background-color: #fff;
	background-position: 260px -61px;
	}

#signup input.error::-webkit-input-placeholder,#signup inputerror :-moz-placeholder 
	{
	color: #f2f2f2;
	}

input[type="submit"]
	{
	background: #00C492;
	border:none;
	width:200px;
	margin:auto;
	float:right;
	padding:5px;
	border-radius:5px;
	color:#fff;
	font-weight:bold;
	cursor:pointer;
	}

Yet your form, validated with HTML5 has been created, but if you want some more feature, You can add a H5F JavaScript library also. Here you can find the script.

JavaScript for validating HTML5 Form

var H5F = H5F || {};

(function(d){
	
	var field = d.createElement("input"),
		emailPatt = new RegExp("([a-z0-9_.-]+)@([0-9a-z.-]+).([a-z.]{2,6})","i"), 
		urlPatt = new RegExp("^http://","i"),
		usrPatt, curEvt, args;
	
	H5F.setup = function(form,settings) {
		var isCollection = !form.nodeType || false;
		
		var opts = {
			validClass : "valid",
			invalidClass : "error",
			requiredClass : "required"
        };

        if(typeof settings === "object") {
			for (var i in opts) {
				if(typeof settings[i] === "undefined") { settings[i] = opts[i]; }
			}
		}
		
		args = settings || opts;
		
		if(isCollection) {
			for(var k=0,len=form.length;k<len;k++) {
				H5F.validation(form[k]);
			}
		} else {
			H5F.validation(form);
		}
	};
	
	H5F.validation = function(form) {
		var	f = form.elements,
			flen = f.length,
			isRequired;
		
		H5F.listen(form,"invalid",H5F.checkField,true);
		H5F.listen(form,"blur",H5F.checkField,true);
		H5F.listen(form,"input",H5F.checkField,true);
		H5F.listen(form,"focus",H5F.checkField,true);
		
		if(!H5F.support()) { 
			form.checkValidity = function(e,f) { H5F.checkValidity("",form); };
			
			while(flen--) {
				isRequired = !!(f[flen].attributes["required"]);
				// Firefox includes fieldsets inside elements nodelist so we filter it out.
				if(f[flen].nodeName !== "FIELDSET" && isRequired) {
					H5F.validity(f[flen]); // Add validity object to field
				}
			}
		}
	};
	H5F.validity = function(el) {
		var elem = el,
			missing = H5F.valueMissing(elem),
			type = elem.getAttribute("type"),
			pattern = elem.getAttribute("pattern"),
			placeholder = elem.getAttribute("placeholder"),
			isType = /^(email|url|password)$/i,
			fType = ((isType.test(type)) ? type : ((pattern) ? pattern : false)),
			patt = H5F.pattern(elem,fType),
			step = H5F.range(elem,"step"),
			min = H5F.range(elem,"min"),
			max = H5F.range(elem,"max");
		
		elem.validity = {
			patternMismatch: patt,
			rangeOverflow: max,
			rangeUnderflow: min,
			stepMismatch: step,
			valid: (!missing && !patt && !step && !min && !max),
			valueMissing: missing
		};
		
		if(placeholder && curEvt !== "input") { H5F.placeholder(elem); }
		elem.checkValidity = function(e,el) { H5F.checkValidity(e,elem); };
	};
	H5F.checkField = function (e) {
		var el = H5F.getTarget(e) || e, // checkValidity method passes element not event
			events = /^(input|focusin|focus)$/i;
		
		curEvt = e.type;
		if(!H5F.support()) { H5F.validity(el); }
		
		if(el.validity.valid) {
			H5F.removeClass(el,args.invalidClass);
			H5F.removeClass(el,args.requiredClass);
			H5F.addClass(el,args.validClass);
		} else if(!events.test(curEvt)) {
			if(el.validity.valueMissing) {
				H5F.removeClass(el,args.invalidClass);
				H5F.removeClass(el,args.validClass);
				H5F.addClass(el,args.requiredClass);
			} else {
				H5F.removeClass(el,args.validClass);
				H5F.removeClass(el,args.requiredClass);
				H5F.addClass(el,args.invalidClass);
			}
		} else if(el.validity.valueMissing) {
			H5F.removeClass(el,args.requiredClass);
			H5F.removeClass(el,args.invalidClass);
			H5F.removeClass(el,args.validClass);
		}
	};
	H5F.checkValidity = function (e,el) {
		var f, ff, isRequired, invalid = false;
		
		if(el.nodeName === "FORM") {
			f = el.elements;
			
			for(var i = 0,len = f.length;i < len;i++) {
				ff = f[i];
				
				isRequired = !!(ff.attributes["required"]);
				
				if(ff.nodeName !== "FIELDSET" && isRequired) {
					H5F.checkField(ff);
					if(!ff.validity.valid && !invalid) {
						ff.focus();
						invalid = true;
					}
				}
			}
		} else {
			H5F.checkField(el);
			return el.validity.valid;
		}
	};
	
	H5F.support = function() {
		return (H5F.isHostMethod(field,"validity") && H5F.isHostMethod(field,"checkValidity"));
	};

	// Create helper methods to emulate attributes in older browsers
	H5F.pattern = function(el, type) {
		if(type === "email") {
			return !emailPatt.test(el.value);
		} else if(type === "url") {
			return !urlPatt.test(el.value);
		} else if(!type || type === "password") { // Password can't be evalutated.
			return false;
		} else {
			usrPatt = new RegExp(type);
			return !usrPatt.test(el.value);
		}
	};
	H5F.placeholder = function(el) {
		var placeholder = el.getAttribute("placeholder"),
			focus = /^(focus|focusin)$/i,
			node = /^(input|textarea)$/i,
			isNative = !!("placeholder" in field);
		
		if(!isNative && node.test(el.nodeName)) {
			if(el.value === "") {
				el.value = placeholder;
			} else if(el.value === placeholder && focus.test(curEvt)) {
				el.value = "";
			}
		}
	};
	H5F.range = function(el,type) {
		// Emulate min, max and step
		var min = parseInt(el.getAttribute("min"),10) || 0,
			max = parseInt(el.getAttribute("max"),10) || false,
			step = parseInt(el.getAttribute("step"),10) || 1,
			val = parseInt(el.value,10),
			mismatch = (val-min)%step;
		
		if(!H5F.valueMissing(el) && !isNaN(val)) {
			if(type === "step") {
				return (el.getAttribute("step")) ? (mismatch !== 0) : false;
			} else if(type === "min") {
				return (el.getAttribute("min")) ? (val < min) : false;
			} else if(type === "max") {
				return (el.getAttribute("max")) ? (val > max) : false;
			} 
		} else if(el.getAttribute("type") === "number") { 
			return true;
		} else {
			return false;
		}
	};
	H5F.required = function(el) {
		var required = !!(el.attributes["required"]);
		
		return (required) ? H5F.valueMissing(el) : false;
	};
	H5F.valueMissing = function(el) {
		var placeholder = el.getAttribute("placeholder");
		return !!(el.value === "" || el.value === placeholder);
	};
	
	/* Util methods */
	H5F.listen = function (node,type,fn,capture) {
		if(H5F.isHostMethod(window,"addEventListener")) {
			/* FF & Other Browsers */
			node.addEventListener( type, fn, capture );
		} else if(H5F.isHostMethod(window,"attachEvent") && typeof window.event !== "undefined") {
			/* Internet Explorer way */
			if(type === "blur") {
				type = "focusout";
			} else if(type === "focus") {
				type = "focusin";
			}
			node.attachEvent( "on" + type, fn );
		}
	};
	H5F.preventActions = function (evt) {
		evt = evt || window.event;
		
		if(evt.stopPropagation && evt.preventDefault) {
			evt.stopPropagation();
			evt.preventDefault();
		} else {
			evt.cancelBubble = true;
			evt.returnValue = false;
		}
	};
	H5F.getTarget = function (evt) {
		evt = evt || window.event;
	    return evt.target || evt.srcElement;
	};
	H5F.addClass = function (e,c) {
		var re;
        if (!e.className) {
			e.className = c;
        }
        else {
	        re = new RegExp('(^|\s)' + c + '(\s|$)');
			if (!re.test(e.className)) { e.className += ' ' + c; }
        }
	};
	H5F.removeClass = function (e,c) {
		var re, m;
		if (e.className) {
			if (e.className == c) {
				e.className = '';
			}
			else {		
				re = new RegExp('(^|\s)' + c + '(\s|$)');
				m = e.className.match(re);
				if (m && m.length == 3) { e.className = e.className.replace(re, (m[1] && m[2])?' ':''); }
			}
		}
	};
	H5F.isHostMethod = function(o, m) {
		var t = typeof o[m], reFeaturedMethod = new RegExp('^function|object$', 'i');
		return !!((reFeaturedMethod.test(t) && o[m]) || t == 'unknown');
	};

})(document);

That’s all done now. If you want to download the HTML5 form validation script, you can download it by clicking on any of the download button on this page. Or if you want to play with any of the scripts, you can do it by clicking on the try it button.



  • శ్రీనివాస్ రజనీకాంత్

    so nice

    ur code helped me alot…………thanks

  • Pinky

    owww……………..superb fantastic ….i loved……it

  • Jay

    Can anyone post a php mysql code for saving datas to DB in local host

  • Vijay Viju

    getting problen with phone number

Show Buttons
Hide Buttons