Skip to content

Instantly share code, notes, and snippets.

@TCotton
Last active December 12, 2015 09:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TCotton/4749123 to your computer and use it in GitHub Desktop.
Save TCotton/4749123 to your computer and use it in GitHub Desktop.
A reusable JavaScript form class
;(function(window){
// for browsers without navite bind support
if (!Function.prototype.bind) {
Function.prototype.bind = function (oThis) {
if (typeof this !== "function") {
// closest thing possible to the ECMAScript 5 internal IsCallable function
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function () {},
fBound = function () {
return fToBind.apply(this instanceof fNOP && oThis ? this : oThis, aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
}
// for browsers without native indexOf support on arrays
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
"use strict";
if (this == null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 1) {
n = Number(arguments[1]);
if (n != n) { // shortcut for verifying if it's NaN
n = 0;
} else if (n != 0 && n != Infinity && n != -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
}
}
// standard cross-browser event
function addEvent(el, type, fn) {
if (window.addEventListener) {
el.addEventListener(type, fn, false);
} else if (window.attachEvent) {
el.attachEvent('on' + type, fn);
} else {
el['on' + type] = fn;
}
}
window.FormClass = function (name) {
'use strict';
this.formName = name;
this.formRequired = {};
this.validationIndValues = {};
this.formRequiredMessage = [];
this.formMessages = [];
this.message = [];
};
FormClass.prototype.required = function (id, message) {
'use strict';
this.formRequired[id] = message;
};
FormClass.prototype.validationInd = function (id, action) {
'use strict';
this.validationIndValues[id] = action;
};
FormClass.prototype.errorMessage = function (message) {
'use strict';
if (message.length !== 0) {
// do something with the error messages here
alert(message.toString());
} else {
this.save();
}
};
FormClass.prototype.save = function () {
'use strict';
var form = document.forms[this.formName], x, l;
// save form here
for (x = 0, l = form.elements.length; x < l; x += 1) {
// do not save unwanted form fields like submit
if (form.elements[x].type !== 'fieldset' && form.elements[x].type !== 'legend' && form.elements[x].type !== 'submit' && form.elements[x].type !== 'hidden') {
// do something with saved form values here
}
}
};
FormClass.prototype.validation = function () {
'use strict';
var validForm = function (event) {
var i, l, anArray = [],
e = event || window.event,
doc = document,
key;
for (key in this.formRequired) {
// loop through ruleList object literals
if (this.formRequired.hasOwnProperty(key)) {
// check if any of the required values are empty
if (doc.querySelector('input#' + key).value === '') {
anArray.push(this.formRequired[key]);
} // end if
} // end if
}
for (key in this.validationIndValues) {
// loop through ruleList object literals
if (this.validationIndValues.hasOwnProperty(key)) {
if (this.validationIndValues[key].match(/email/g)) {
// check if valid email address
if (!doc.querySelector('input#' + key).value.match(/^(.+)@([^\(\);:,<>]+\.[a-zA-Z]{2,4})/)) {
anArray.push('You have entered an incorrect email address');
}
}
if (this.validationIndValues[key].match(/minimum/g)) {
// check if number of characters is less than specified
if (parseInt(doc.querySelector('input#' + key).value.length) < parseInt(this.validationIndValues[key].match(/\d+\.?\d*/g))) {
anArray.push(this.validationIndValues[key]);
}
}
if (this.validationIndValues[key].match(/maximum/g)) {
// check if number of characers is more than specified
if (parseInt(doc.querySelector('input#' + key).value.length) > parseInt(this.validationIndValues[key].match(/\d+\.?\d*/g))) {
anArray.push(this.validationIndValues[key]);
}
}
}
} // end for loop
this.errorMessage(anArray);
// cross-brower prevent default
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
e.cancelBubble = true;
}
};
// use bind to add bypass JavaScript scope and to be able to directly
// access the FormClass object
addEvent(document.forms[this.formName], 'submit', validForm.bind(this));
};
})(window);
window.onload = function () {
if (document.querySelector) {
// name attribute of form
var contactForm = new FormClass('contactUs');
// id attribute of form elements
// use required if the form field is essential
contactForm.required('contact-name', 'Please fill in your contact name');
contactForm.required('contact-email', 'Please fill in your email address');
// id attribute of form elements
// use validationInd to create individual form field validation
contactForm.validationInd('contact-email', 'email');
contactForm.validationInd('contact-name', 'Please enter a minimum of 10 characters for a contact name');
// use validation to run validation function
// will produce error messages or save form if okay
contactForm.validation();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment