Skip to content

Instantly share code, notes, and snippets.

Created August 29, 2014 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/9a0f02ee5341d9b7a670 to your computer and use it in GitHub Desktop.
Save anonymous/9a0f02ee5341d9b7a670 to your computer and use it in GitHub Desktop.
//Validator
adrma.Validate = function() {
if (this instanceof adrma.Validate) {
return this;
} else {
return new adrma.Validate();
}
};
adrma.Validate.prototype = {
defaults: {
errorClass: "error",
fieldContainer: "label",
formEle: ""
},
init: function init(config) {
var self = this;
$.extend(this, this.defaults, config);
self.formEle = $(self.formEle);
if (self.hasFormValidation()) {
// still need to decide what to do.. (perhaps allow config to bypass or pass adrma.Validate)
};
self.formEle.on("submit", function() {
return self.validate(self.formEle);
});
return this;
},
validate: function validate(formEle) {
var self = this,
inputs = formEle.find(":input:visible"),
input,
inputValid,
valid = true;
inputs.each(function(i, e) {
inputValid = self.validateInput(e);
if (!inputValid) {
valid = false;
}
});
return valid;
},
clearValidationErrors: function clearValidationErrors(formEle) {
formEle = formEle || this.formEle;
formEle.find(":input").removeClass("error");
formEle.find(".message.error").remove();
},
validateInput: function validateInput(fieldEle) {
var self = this,
input = $(fieldEle),
val = input.val(),
type = input.attr("type"),
name = input.attr("name"),
pattern = input.attr("pattern"),
maxLength = input.attr("data-max-length"),
minLength = input.attr("data-min-length"),
required = input.attr("required"),
validateErrorMessage = input.attr("data-validate-error"),
valid = true,
regExpRefAttr = input.attr("data-regexp-ref"),
regExpRef = regExpRefAttr,
regExp,
regExpMap = adrma.regExp,
fieldContainer = input.closest(self.fieldContainer);
fieldContainer = fieldContainer.length ? fieldContainer : input;
if (required && (!val || val.length === 0 || !val.trim())) {
valid = false;
validateErrorMessage = "required";
} else if ((required || val) && type === "text" && !regExpMap.text.test(val)) {
valid = false;
validateErrorMessage = "Standard US Characters Required";
} else if ((required || val) && (regExpMap[type] || pattern || regExpRef)) {
if (pattern) {
regExpRef = new RegExp(pattern);
} else {
regExpRef = regExpMap[regExpRef] || regExpMap[type];
}
if (type === "zip" && !regExpRefAttr) {
// temp fix for zip validation (defualts to US)
regExpRef = regExpMap.usZip;
}
if (regExpRef && regExpRef.test) {
valid = regExpRef.test(val);
}
if (!valid) {
validateErrorMessage = validateErrorMessage || "invalid value";
}
} else {
valid = required ? val : true;
}
// for phone we should check only count of digits
if (name == "phone") {
val = val.match(/\d/g);
}
if (valid && maxLength) {
valid = val.length <= maxLength;
validateErrorMessage = "Value shouldn't be longer than " + maxLength + " chars";
}
if (valid && minLength) {
valid = val.length >= minLength;
validateErrorMessage = "Value shouldn't be shorter than " + minLength + " chars";
}
fieldContainer.find(".message.error").remove();
if (!valid) {
fieldContainer.append("<span class='message error'>" + validateErrorMessage + "</span>");
}
fieldContainer[(valid ? "remove" : "add") + "Class"](self.errorClass);
return valid;
},
hasFormValidation: function hasFormValidation() { // has built in form validation http://bit.ly/19MuXLX
return (typeof document.createElement('input').checkValidity == 'function');
},
onValidationError: function onValidationError(formEle, response) {
var self = this,
ele;
formEle = $(formEle); // wrap in jQuery in case its a selector string.
formEle.find(".message.error").remove();
formEle.find(".error").removeClass("error");
$.each(response.messages, function(i, e) {
if (e.field === "general") {
ele = formEle;
} else {
ele = formEle.find("[name='" + e.field + "']");
}
self.applyFeildError(ele, e.text);
});
},
applyFeildError: function applyFeildError(ele, errorText, method) {
errorText = errorText || "";
var label = ele.closest("label");
label = label.length ? label : ele; // it is posible to pass in a container..
label.addClass("error");
method = method || "after";
label[method]("<p class='message error'>" + errorText + "</p>");
}
};
// All regexes that can be tested against.
// http://bit.ly/10bQnBF
adrma.regExp = {
url: /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)/,
cc: /^[0-9]{16}$/,
datetime: /^([0-2][0-9]{3})\-([0-1][0-9])\-([0-3][0-9])T([0-5][0-9])\:([0-5][0-9])\:([0-5][0-9])(Z|([\-\+]([0-1][0-9])\:00))$/,
email: /^(([^<>()[\]\\.,;:\s@\"!#$%^&*]+(\.[^<>()[\]\\.,;:\s@\"!#$%^&*]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
tel: /^((\+\d{1,3}(-|.| )?\(?\d\)?(-|.| )?\d{1,3})|(\(?\d{2,3}\)?))(-|.| )?(\d{3,4})(-|.| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/,
zip: {
'us': /^(\d{5}([\-]\d{4})?)$/ // should be removed once tested...
},
usZip: /^\d{5}$/,
caZip: /^[ABCEGHJKLMNPRSTVXY][0-9][A-Z][\s-]?[0-9][A-Z][0-9]$/i,
otherZip: /^[a-zA-Z0-9-&,'%$".\s]{3,}$/,
usCurrency: /^[+-]?[0-9]{1,3}(?:,?[0-9]{3})*(?:\.[0-9]{1,2})?$/,
text: /^[a-zA-Z0-9\s&@-_'"(),.#\/+-]+$/
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment