1

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.

2
  • you want something like this? jsfiddle.net/ZeKxk Commented Jan 4, 2013 at 12:59
  • In the end I used jQuery widget factory. It just seemed a lot more straightforward. Commented Jan 8, 2013 at 22:24

1 Answer 1

1

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

$.fn.valid = function() {
    return $(this).regexField("valid");
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for this, however I now realise doing things like this is bad, bad, bad as it clutters up the jQuery namespace. I suppose a better way to do this would be $('#inp').regexField('valid') Thanks for you help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.