Justin Fay
Justin Fay

Reputation: 2606

Refactoring jQuery plugin

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.

I have put up a working sample of where I currently am at here http://jsfiddle.net/WpvMB/

And for completeness here is my plugin code (full of what I am assuming are terrible design decision although it does work)

(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 );

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.

$('#textinput').regexField({'regex': /^[0-9]+$/})
$('#textinput').valid()
>>> true

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.

Upvotes: 1

Views: 158

Answers (1)

Taha Paksu
Taha Paksu

Reputation: 15616

Add this inside your plugin and it'll work as you wish:

$.fn.valid = function() {
    return $(this).regexField("valid");
}

Upvotes: 1

Related Questions