我正在写一个jQuery插件在表单字段上做正则表达式验证。这是我编写的第一个jQuery插件,我发现许多不同的教程和插件设计模式令人困惑。
我已经把我目前在这里的工作样本放到了http://jsfiddle.net/WpvMB/
为了完整,这里是我的插件代码(充满了我认为是糟糕的设计决策,尽管它确实可以工作)
(function( $ ){
var settings = {}
var methods = {
init : function( options ) {
settings = $.extend( {
'error_class': 'error',
'success_class': 'success',
'regex': /.*/,
}, options);
this.bind('keyup focusout focusin', methods.doValidate);
},
valid : function( ) {
if ( $(this).val().match( settings.regex ) ) {
return true
}
return false
},
doValidate: function( ) {
if ( $(this).regexField('valid') ) {
$(this).addClass( settings.success_class )
$(this).removeClass( settings.error_class )
} else {
$(this).removeClass( settings.success_class )
$(this).addClass( settings.error_class )
}
},
};
$.fn.regexField = function( method ) {
if ( methods[method] ) {
return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.regexField' );
}
};
})( jQuery );
理想情况下,我希望插件能够像现在一样工作,并且还能够调用元素上的有效方法并接收true/false结果,例如。
$('#textinput').regexField({'regex': /^[0-9]+$/})
$('#textinput').valid()
>>> true
任何关于什么特定的插件模式适合这种类型的插件的输入都是非常感谢的,就像对现有代码的任何反馈一样。
发布于 2013-01-04 21:01:25
将这个代码添加到你的插件中,它就会像你所希望的那样工作:
$.fn.valid = function() {
return $(this).regexField("valid");
}
https://stackoverflow.com/questions/14157385
复制相似问题