Skip to content

Instantly share code, notes, and snippets.

@iloveitaly
Created August 24, 2010 19:53
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save iloveitaly/548187 to your computer and use it in GitHub Desktop.
function isValidEmail(email) { return /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email); }
var InputValidator = new Class({
options: {
errorColor: 'red',
errorClass: 'error_text',
ignoreDisabled: false,
auxElementPadding: '1em'
},
/*
Function: initialize
Arguments:
element - the element to error check
type - the type of error checking to perform (zip, email)
errorMessage - the error message to display
*/
initialize: function(options) {
this.setOptions(options);
// make sure the target element is extended
this.options.element = $(this.options.element);
// attach events to auto-eliminate the error messages
// input[type=password], select, and file ALWAYS use aux field
if(this.options.element.get('tag') == "select" ||
(this.options.element.get('tag') == "input" && this.options.element.get('type') == "password")) {
this.options.element.addEvent('change', function() {
if(this.options.element.get('value')) {
if(this.options.errorElement) this.options.errorElement.setHTML('');
}
}.bind(this));
this.useAux = true;
} else if(this.options.element.get('tag') == "input" && this.options.element.get('type') == "file") {
this.useAux = true;
} else {
this.options.element.addEvent('focus', function(event) {
event = new Event(event);
if(event.target.getStyle('color') == this.options.errorColor) {
event.target.setStyle('color', 'black');
event.target.value = event.target.retrieve('_value');
}
}.bind(this));
this.useAux = false;
}
},
test: function() {
var isInvalid = false;
if(this.options.ignoreDisabled && this.options.element.disabled == true) {
return true;
}
switch(this.options.type) {
case "email":
if(!isValidEmail(this.options.element.get('value'))) {
isInvalid = true;
}
break;
case "zip":
if(this.options.element.get('value').length < 5 || this.options.element.get('value') == this.options.errorMessage) {
isInvalid = true;
}
break;
default:
if(this.options.element.get('tag') == "textarea") {
isInvalid = this.options.element.value.length == 0 || this.options.element.value == this.options.errorMessage;
} else if(this.options.element.get('tag') == "input" && this.options.element.getAttribute('type') == "file") {
isInvalid = this.options.element.value.length == 0;
} else if(this.options.element.get('value').length == 0 || this.options.element.get('value') == this.options.errorMessage) {
isInvalid = true;
}
break;
}
if(!isInvalid && this.options.confirmElement) {
if(this.options.element.get('value') != this.options.confirmElement.get('value'))
isInvalid = true;
}
if(!isInvalid) {
return true;
}
var tagName = this.options.element.get('tag');
if(!this.useAux) {
this.options.element.setStyle('color', this.options.errorColor);
if(this.options.element.get('tag') == "textarea") {
this.options.element.set('html', this.options.errorMessage);
} else {
if(this.options.element.get('value') != this.options.errorMessage) {
this.options.element.store('_value', this.options.element.get('value'));
this.options.element.set('value', this.options.errorMessage);
}
}
} else {
if(!Browser.Engine.trident4) {
if(!this.options.errorElement) {
this.options.errorElement = new Element("span", {
'class': this.options.errorClass,
'styles': {
'padding-left':this.options.auxElementPadding},
'html':'&nbsp;'
}
);
this.options.errorElement.injectAfter(this.options.element);
}
this.options.errorElement.set('html', this.options.errorMessage);
}
}
return false;
}
});
InputValidator.implement(new Options);
// auto validator storage
var _forms = {}
var _validators = {};
var _labels = {};
// elementID: the id to search through for form elements with class="required"
// validatorOptions: options to be passed to each individual validator
function createInputValidators(elementID, globalValidatorOptions) {
// find all forms or zero in on that one form
$$(elementID ? '#' + elementID : 'form').each(function(formElement) {
formName = formElement.getProperty("id") ? formElement.getProperty("id") : formElement.getProperty("name");
_validators[formName] = {};
_labels[formName] = [];
_forms[formName] = formElement;
formElement.getElements("label").each(function(formLabel) {
var key = formLabel.getProperty("for") ? formLabel.getProperty("for") : formLabel.get("text").toLowerCase().split(" ").join("_");
_labels[formName][key] = formLabel;
});
// attach the class 'required' to input/select elements to automatically create a InputValidator
// for them. Use the alt tag to specify a custom error message
formElement.getElements(".required").each(function(inputElement) {
var name = inputElement.getProperty('name');
var type = '';
var localValidatorOptions = {
element:inputElement
};
// add a required * to each element that is required
var asterisk = new Element('span', {
'class':'error_text',
'html':'*',
'styles':{'font-size':'1.1em'}
});
// we dont want it on the right side anymore
// if we have an label insert a * on left side (the 'top')
if(_labels[formName][name]) asterisk.injectTop(_labels[formName][name]);
// try to guess the type
if(name.indexOf('email') != -1) {
localValidatorOptions.type = 'email';
} else if(name.indexOf('date')) {
}
// check if it is a 'confirm' field
if(name.indexOf('confirm_') == 0) {
localValidatorOptions.confirmElement = _validators[formName]['email'].options.element;
}
var errorString = '';
if(errorString = inputElement.getProperty('alt')) {
// then an error string was determined for us
} else {
// then determine the error string
// convert underscores to spaces
name = name.split("_").join(" ");
// change the error message for select elements
if(inputElement.get('tag') == "select") {
errorString = " Please select a " + name + "...";
} else {
errorString = "Enter a " + name + "...";
}
}
localValidatorOptions.errorMessage = errorString;
_validators[formName][name] = new InputValidator($merge(
globalValidatorOptions,
localValidatorOptions
));
});
});
return _validators;
}
function linkDisabledState(sourceElement, conditionalElement) {
sourceElement.addEvent('click', function(evn) {
conditionalElement.disabled = !evn.target.checked;
});
conditionalElement.disabled = !sourceElement.checked;
}
function autoValidateForms() {
$each(_forms, function(formElement, formName) {
formElement.addEvent("submit", function(e) {
new Event(e).stop();
var valid = true;
$each(_validators[formName], function(elementValidator) {
valid &= elementValidator.test();
});
if(valid)
this.set('send', {}).submit()
})
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment