I plugin sono il modo migliore per ottimizzare le routine di validazione dei form in jQuery.
Possiamo racchiudere le nostre routine di validazione in un plugin:
(function( $ ) {
$.fn.charsLeft = function( options ) {
options = $.extend({
limit: 30,
validate: function() {},
classes: {
error: "error",
validation: "error"
}
}, options);
var charsLeft = function( element, opts ) {
var max = parseInt( opts.limit, 10 );
element.after( '<div class="chars-left"></div>' );
element.keyup(function() {
var value = $( this ).val();
var textLength = value.length;
var remaining = max - textLength;
element.next().text( remaining );
// Prima routine
if( textLength > max ) {
element.next().addClass( opts.classes.error );
} else {
element.next().removeClass( opts.classes.error );
}
// Seconda routine
opts.validate( value, element, opts );
});
};
return this.each(function() {
var $element = $( this );
charsLeft( $element, options );
});
};
})( jQuery );
Esempio d'uso:
$( function() {
$( "#text" ).charsLeft({
validate: function( val, el, opts ) {
if( !/^[a-z0-9]+$/i.test( val ) ) {
el.addClass( opts.classes.validation );
} else {
el.removeClass( opts.classes.validation );
}
}
});
});