Skip to content

Instantly share code, notes, and snippets.

@renaehodgkins
Created January 24, 2012 20:11
Show Gist options
  • Save renaehodgkins/1672279 to your computer and use it in GitHub Desktop.
Save renaehodgkins/1672279 to your computer and use it in GitHub Desktop.
contact_form
jQuery(document).ready(function() {
validate_contact_form('#contact_form');
});
function validate_contact_form(form){
var validation_fields = ["#first_name", "#last_name", "#company", "#phone"];
jQuery.each(validation_fields, function(index, value){
$(form + ' ' + value).blur(function(){
validate_presence_of(this, form);
})
})
$(form + ' #email').blur(function(){
validate_email_format(this);
})
$(form + ' #phone').blur(function(){
validate_phone_format(this);
})
$(form).submit(function(e){
var valid = false;
jQuery.each(validation_fields, function(index, value){
if(validate_presence_of(value, form) && validate_email_format('#email') && validate_phone_format('#phone')) {
valid = true;
} else {
valid = false;
}
})
if(!valid){ e.preventDefault() }
})
}
function validate_email_format(field){
var reg = /^([A-Za-z0-9_\-\.\+])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if(reg.test($(field).val())) {
remove_validation_error_on(field);
return true;
} else {
add_validation_error_on(field, "<strong>Required:</strong> Please Check");
return false;
}
}
function validate_phone_format(field){
var reg = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
if(reg.test($(field).val())) {
remove_validation_error_on(field);
return true;
} else {
add_validation_error_on(field, "<strong>Required:</strong> Please Check");
return false;
}
}
function validate_presence_of(field){
var reg = /^[a-zA-Z0-9].+/;
if(reg.test($(field).val())){
remove_validation_error_on(field);
return true;
} else {
add_validation_error_on(field, "<strong>Required:</strong> Please Check");
return false;
}
}
function remove_validation_error_on(field){
$(field).removeClass('error');
$(field).siblings('span').replaceWith("<span>&#10003;</span>");
}
function add_validation_error_on(field, message){
$(field).addClass('error');
$(field).siblings('span').replaceWith("<span class='error'>"+message+"</span>");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment