/*indoc form validation - add on load*/ $('document').ready(function(){ //get all form elements which need to be validated $('.formrow input').bind('blur',validateFormElementEvent); $('.formrow select').bind('blur',validateFormElementEvent); $('.formrow textarea').bind('blur',validateFormElementEvent); $('.formrow .submit').bind('click',validateAllForm); function validateFormElementEvent(event){ if($(event.target).attr('type')!="submit"){ validateFormElement(event.target,false); } } function validateFormElement(target,instant){ //first remove all current errors var fieldName=$(target).attr('name'); var error; if(fieldName){ //get validation type var validationType=fieldName.replace(/[^_]+_/,''); if(validationType=="_mandatory" && $(target).val()=="" ){ error="You must fill out this field"; } if(validationType=="_email" && !$(target).val().match(/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/)){ error="This must contain an email address"; } if(validationType=="_phone" && !$(target).val().match(/[0-9 .()+-]{6,20}/)){ error="This must contain a telephone number"; } if(validationType=="_url" && !$(target).val().match(/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/)){ error="This must contain a website address"; } if(validationType=="_age" && (parseInt($(target).val()))>0 && (parseInt($(target).val()))<160 ){ error="This must contain an age"; } if(validationType=="_number" && ($(target).val().match(/[^0-9\., ]+/) || $(target).val().length<1)){ error="This must contain a number "; } } if(error){ //absolutely postion an error near field?, then set a timer to remove them all after 5 seconds? if($(target).parent().find('.formError').length==0){ $(target).after('
'+error+'
'); $(target).next().fadeIn(1000); } }else{ //add tick? $(target).parent().addClass('valid'); if(instant){ $(target).parent().find('.formError').remove(); }else{ $(target).parent().find('.formError').fadeOut(1000,function(){ $(this).remove(); }); } } } function validateAllForm(event){ $(event.target).parents('form').find('input').each(function(index){ if($(this).attr('type')!="submit" && $(this).attr('type')!="hidden"){ validateFormElement($(this),true); } }); $(event.target).parents('form').find('textarea').each(function(index){ validateFormElement($(this),true); }); $(event.target).parents('form').find('select').each(function(index){ validateFormElement($(this),true); }); if($(event.target).parents('form').find('.formError').length>0){ alert('Please correct the errors in the form before sending'); event.preventDefault(); return false; } } });