Note that there are some explanatory texts on larger screens.

plurals
  1. PORefactoring jQuery plugin
    text
    copied!<p>I am writing a jQuery plugin to do regex validation on form fields. This is the first jQuery plugin I have written and I am finding the many different tutorials and plugin design patterns confusing.</p> <p>I have put up a working sample of where I currently am at here <a href="http://jsfiddle.net/WpvMB/" rel="nofollow">http://jsfiddle.net/WpvMB/</a></p> <p>And for completeness here is my plugin code (full of what I am assuming are terrible design decision although it does work)</p> <pre><code>(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 ); </code></pre> <p>Ideally I would like the plugin to function as it does now and to also be able to call a valid method on the element and receive a true/false result, eg.</p> <pre><code>$('#textinput').regexField({'regex': /^[0-9]+$/}) $('#textinput').valid() &gt;&gt;&gt; true </code></pre> <p>Any input on what specific plugin pattern is suitable for this type of plugin is much appreciated as is any feedback on existing code, regards.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload