2

Markup:

<input type="text" name="email" />

Code:

$(':text').focusout(function(){
    $(this).validate(function(){
        $(this).attr('name');
    });
});

Plugin:

(function($){  
    $.fn.validate = function(type) {  
        return this.each(function(type) {  
            if (type == 'email') {
                matches = this.val().match('/.+@.+\..{2,7}/');
                (matches != null) ? alert('valid') : alert('invalid');
            }
            /*else if (type == 'name') {

            }
            else if (type == 'age') {

            }
            else if (type == 'text') {

            }*/
            else {
                alert('total failure');
            }
        });
    };  
})(jQuery);

The problem is that when I execute the code above, it runs the plugin as if type was a string: "function(){ $(this).attr('name'); });" instead of executing it as a function. How do I solve this?

1
  • Calling $(this).validate($(this).attr('name')) ? Also, use $(this).val() instead of this.val(). Commented Apr 11, 2010 at 17:30

1 Answer 1

1

You must check if the parameter is a function. If yes use the return value else assume it's a literal value.

(function($) {
    $.fn.validate = function(type) {
        //check if type type is a function else take it as literal
        type = typeof type !== "function" ? type : type();
        return this.each(function(type) {
            ...
        });
    };
})(jQuery);
Sign up to request clarification or add additional context in comments.

Comments

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.