フォームフィールドで正規表現の検証を行うための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 );
理想的には、プラグインが現在と同じように機能し、要素に対して有効なメソッドを呼び出して、真/偽の結果を受け取ることができるようにしたいと思います。
$('#textinput').regexField({'regex': /^[0-9]+$/})
$('#textinput').valid()
>>> true
このタイプのプラグインに適した特定のプラグインパターンに関する入力は、既存のコードに関するフィードバックと同様に、非常に高く評価されています。