Skip to content

Instantly share code, notes, and snippets.

@phawk
Created May 11, 2011 14:22
Show Gist options
  • Save phawk/966534 to your computer and use it in GitHub Desktop.
Save phawk/966534 to your computer and use it in GitHub Desktop.
<script type="text/javascript">
/*
* Basic reusable form validation
*
* @author Pete Hawkins <[email protected]>
* @created 2011-05-11
* @requires jQuery
*
* Setup:
* Add your fields as objects in an array to the validatorConfig.fields object.
* You may also changes any other items in the validatorConfig object.
*
*/
var validatorConfig = {
// The DOM ID of the form
formID: 'mc-embedded-subscribe-form',
// Array of field objects, with name value ( the DOM ID ) and required ( "yes" / "no" ). more options to come.
fields: [ { name: "email", required: "yes", validEmail: "yes" } ],
// Left unclosed because it adds in a required error class simply change '<div ' to '<li ' etc.
errorPrefix: '<div class="error ',
errorPostfix: '</div>',
// Set the error message text
errorMessages: {
invalidEmail: "The {fieldName} field is an invalid email address",
requiredField: "The {fieldName} field is required."
}
};
var validator = null,
logErrors = true,
i = null,
j = null,
value = null,
keyExists = false;
errorMessage = null,
validationErrors = [],
valid = true;
function preventDefault(e) {
e.preventDefault();
validator.init();
}
// Main validator object
validator = {
init: function() {
// Check if validation passes and submit form or display errors.
if( validator.validate( validatorConfig.fields ) === false )
{
validator.displayErrors();
}
else
{
$( '#' + validatorConfig.formID ).unbind( "submit" ).submit();
}
},
validate: function( fieldsArray ) {
valid = true;
if( fieldsArray.length > 0 ) {
for( i = 0, j = fieldsArray.length; i < j; i++ )
{
if( validator.checkRequired( fieldsArray[ i ] ) === false ) {
valid = false;
}
if( validator.checkValieEmail( fieldsArray[ i ] ) === false ) {
valid = false;
}
}
return valid;
}
},
checkRequired: function( obj ) {
if( obj.required === "yes" ) {
value = $( '#' + obj.name ).val();
if( value !== null && value !== "" )
{
return true;
}
else
{
return validator.checkErrorExists( obj, "requiredField" );
}
}
},
checkValieEmail: function( obj ) {
if( obj.validEmail === "yes" ) {
value = $( '#' + obj.name ).val();
if( value === null || value === "" )
{
// Value is empty. If required, it will catch the error.
return true;
}
else if( value.match(/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix) )
{
// Valid email address
return true;
}
else
{
// Check if the error is alread in the array
return validator.checkErrorExists( obj, "invalidEmail" );
}
}
},
checkErrorExists: function( obj, errorMsgType ) {
// Check if the error is alread in the array
if( validationErrors.length > 0 ) {
for( i = 0, j = validationErrors.length; i < j; i++ )
{
keyExists = false;
testObj = validationErrors[ i ];
if( testObj.name === obj.name ) {
testObj.errorType = errorMsgType;
keyExists = true;
}
}
}
// Add the validation error to an array
if( keyExists === false )
{
validationErrors.push( { name: obj.name, errorType: errorMsgType } );
}
return false;
},
displayErrors: function() {
// Display the form errors below the fields
if( validationErrors.length > 0 ) {
for( i = 0, j = validationErrors.length; i < j; i++ )
{
value = validationErrors[ i ];
// Parse the error message strings with the field value
errorMessage = validatorConfig.errorMessages[ value.errorType ].replace("{fieldName}",String(value.name));
validator.logError( errorMessage );
// Check if the element exists in the DOM
if( $( '.' + value.name + '-error' ).length < 1 ) {
$( '#' + value.name ).after( validatorConfig.errorPrefix + value.name + '-error">' + errorMessage + validatorConfig.errorPostfix );
}
else
{
$( '.' + value.name + '-error' ).html( errorMessage );
validator.flashError( value.name );
}
}
}
},
flashError: function( fieldName ) {
$( '.' + fieldName + '-error' ).fadeOut( 'fast' ).fadeIn( 'slow' );
},
logError: function( error, field ) {
if( logErrors === true ) {
console.log( '> Validator[' + field + ']: ' + error );
}
}
};
$(document).ready(function(){
$( '#' + validatorConfig.formID ).bind( "submit", preventDefault );
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment