You can implement Strategy design pattern, implement your validation as default strategy and let the user to implement custom strategies. User may configure your component with other validation strategy (e.g. pass it as one of the configuration properties or by setting relevant property of the component after it was instantiated). Below you can find an example:
$(function() {
$.widget( "custom.mycomponent", {
options: {
validate: null
},
_validate: function() {
return true;
},
_create: function() {
this.options.validate = this.options.validate || this._validate;
var that = this;
this.element.on('keypress', function() {
if(that.option('validate')()) {
this.style.backgroundColor = 'green';
} else {
this.style.backgroundColor = 'red';
}
});
},
_setOptions: function() {
this._superApply( arguments );
},
_setOption: function(key, value) {
switch(key) {
case 'validate':
if(typeof value !== 'function') return;
}
this._super( key, value );
}
});
// Instantiate with default options
$('#my-component1').mycomponent();
// Pass another validation strategy
$('#my-component2').mycomponent({validate: function() {return false;}});
});
Working example in action http://jsbin.com/inavur/4/edit