Form validation is so important from a usability point of view, this is a form hoping to encapsulate all form elements and how we validate them on the front end to prevent an erroneous form submission, in other words getting all the information correct before sending it off. Try using the form below:
The code behind this form validation is shown below as you can see we have just a few validators but can be easily extended.
awl.validation = new (function(){
/*
* Desc: This will validate any form element with an attribute of data-rule, this can be extended to support any amount of rules you need to define.
*
*/
/* PUBLIC */
this.init = function (){
//onsubmit run validation
jQuery("form.awlValidate").submit(function(e){
if(!validateForm(jQuery("form *[data-rule]"),this)) {
e.preventDefault();
} else {
alert("Success, normally we would now submit the form, as this is just a demo we wont bother.");
}
//temp fix REMOVE THIS
e.preventDefault();
});
}
/* Private */
function validateForm(fe,f) {
//hide old errors
hideErrors();
var rules = 0,
errors = {};
fe.each(function(i,e){
var type = e.getAttribute("data-rule"),
val = e.value;
var aValidator = type.split("|");
for(var i=0;i<aValidator.length;i++){
rules++;
switch(aValidator[i]) {
case 'populated':
if(val.trim().length) {
//remove the rule
rules--;
} else{
//put error in errors obj
errors[e.id] = 'Empty field.';
}
break;
case 'email':
if(errors[e.id]){
continue;
}
if(isEmailAddress(val)) {
//remove the rule
rules--;
} else {
//put error in errors obj
errors[e.id] = 'Invalid email format.';
}
break;
case 'num':
if(!isNaN(val)) {
//remove the rule
rules--;
} else {
//put error in errors obj
errors[e.id] = 'Numbers only please.';
}
break;
default:
}
}
});
if (rules) {
//show errors
showErrors(errors,f)
return false;
} else {
return true;
}
}
function showErrors(er,f) {
// error message string
var emString = '<div class="errors errors_'+f.id+'"><p>Oops, please fix the errors highlighted below</p></div>';
jQuery(f).before(emString);
//loop through errors and build error HTML
var erPoints = '<ul class="errorList">';
for (x in er) {
erPoints += '<li><label for="'+x+'">'+er[x]+'</label></li>';
//also flag error ele
jQuery("#"+x).parent().addClass("errorEle");
}
erPoints += '</ul>';
//show points
jQuery(".errors_"+f.id).append(erPoints);
}
function hideErrors() {
//hide all errors on page
jQuery(".errorEle").removeClass("errorEle");
jQuery(".errors").remove();
}
function isEmailAddress(str) {
var pattern = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,4}$/;
if(str.match(pattern)) {
return true;
} else {
return false;
}
}
});
Leave A Comment