Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
JS Validate script
'use strict';
var sr = {};
sr.Validator = function(){
this.errors = [];
this.messages = {
required: 'The :input: is required',
email: 'The :input: is not a valid email address',
mobile: 'The :input: is not a valid mobile number',
hex: 'The :input: is not a valid hex code',
min: 'The min value of :input: is :num:',
max: 'The max value of :input: is :num:'
};
this.initialize = function(){
this.els = document.getElementsByClassName('validate');
};
this.call = function(){
this.setRules();
this.showErrors();
};
this.setError = function(el, message, num){
el.className += ' error';
var msg = message.replace(':input:', el.getAttribute('name'));
return msg.replace(':num:', num);
};
this.setRules = function(){
for (var i = 0; i < this.els.length; i++) {
this.els[i].className = 'validate';
var rules = this.els[i].getAttribute('data-validate').split('|');
this.validate(this.els[i], rules);
}
};
this.validate = function(el, rules){
for (var i = 0; i < rules.length; i++) {
if (rules[i].indexOf(':') !== -1) {
var limit = rules[i].split(':');
this[limit[0]](el, limit[1]);
} else {
this[rules[i]](el);
}
}
};
this.showErrors = function(){
if(this.errors.length > 0){
var err = document.getElementById('errors');
err.innerHTML = null;
for (var i = 0; i < this.errors.length; i++) {
err.innerHTML += '<li>' + this.errors[i] + '</li>';
}
this.errors = [];
event.preventDefault();
}
};
/*-----------------------------------
| Validation Rules
------------------------------------*/
this.required = function(el){
if(el.value.length === 0){
this.errors.push(this.setError(el, this.messages.required));
}
};
this.email = function(el){
var rule = /^[\w-.+]+?@.+\.[a-z]{2,4}$/i;
if(!rule.test(el.value)){
this.errors.push(this.setError(el, this.messages.email));
}
};
this.mobile = function(el){
var rule = /^(\+)?[\d]{11,12}$/;
if (!rule.test(el.value)) {
this.errors.push(this.setError(el, this.messages.mobile));
}
};
this.hex = function(el){
var rule = /^#?(([a-fA-F0-9]){3}){1,2}$/;
if (!rule.test(el.value)) {
this.errors.push(this.setError(el, this.messages.hex));
}
};
this.min = function(el, num){
if(el.value < num){
this.errors.push(this.setError(el, this.messages.min, num));
}
};
this.max = function(el, num){
if(el.value > num){
this.errors.push(this.setError(el, this.messages.max, num));
}
};
this.initialize();
};
(function(){
window.v = new sr.Validator();
document.getElementById('form').addEventListener('submit', function() {
window.v.call();
}, false);
})();
@clarkeash
Copy link

clarkeash commented Apr 23, 2013

what does var sr = {}; do?

@steve228uk
Copy link
Author

steve228uk commented Apr 24, 2013

Namespaces the plugin to the sr object. If someone else has a var Validator then it won't be overwritten.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment