So I’ve just built this small little jQuery validation system and thought I would share it. It’s transparent in the sense that it is a system for testing validation. It doesn’t do anything on detection, it just tells you. Features:
[LIST]
[]Access in two ways (through function & selector)
[]Supports regex testing
[]Allows for length testing
[]Clean HTML
[*]Simple and Extendable
[/LIST]
Example:
Name: <input type="text" name="username" rel="[5, 15]" />
Email: <input type="text" name="email" class="email" />
With this, the username field has to have a length between 5 and 15, and the email field is checked to be an email. Clean HTML, right? What about the Javascript? There’s a few ways to use it but this is how I plan on using it:
$('form').submit(function() {
if($(this).find('input:invalid').length != 0) {
// Do extra stuff here (select invalid forms with $(this).find('input:invalid')
return false;
}
});
Source:
jQuery.validators = {
url: /^(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&%\$#_]*)?$/,
number: /^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$/,
string: /[a-zA-Z]+/,
email: /^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$/
}
jQuery.fn.validate = function() {
i = 0;
target = jQuery(this)[0];
if(/input/i.test(target.nodeName)) {
jQuery.each(jQuery.validators, function(x, y) {
if(jQuery(target).hasClass(x) && !y.test(jQuery(target).attr('value'))) {
i++;
}
});
} else { i++; }
if(jQuery(target).attr('rel') != undefined && /\[.*\]/.test(jQuery(target).attr('rel'))) {
params = jQuery(target).attr('rel').replace(/\[/, '');
params = params.replace(/\]/, '');
params = params.replace(/ /, '');
params = params.split(',');
length = jQuery(this).attr('value').length
if(params.length == 1 && length < params[0]) {
i++;
} else if(params.length == 2 && (length < params[0] || params[1] < length)) {
i++;
}
}
return (i == 0) ? true : false;
};
$.extend($.expr[':'], {
valid: "$(a).validate();",
invalid: "!$(a).validate();"
});