Leon
Leon

Reputation: 149

Using jQuery Validate rules to mark required fields

I've implemented the jQuery validation plugin from bassistance.de and use it by manually defining rules below each form I'd like to have validated. I would like to modify the fields (eg. give them a border-color) that I defined as required after the script initialisation is done, but I can't seem to find a generic 'loaded' callback, event or extending possibilities.

Is there a way to perform a script each time that $('#form').validate(..) is finished initializing?

The way I'm solving it right now is as follows:

$(document).ready(function() {
    $('#myForm').validate({
        rules: {
            txtCode: { required: true, maxlength: 12 },
            txtName: { required: true, maxlength: 50 },
        }
    });
    $('#myForm').highlightRequiredFields();
});

.. where highlightRequiredFields() is a simple jQuery plugin I wrote to modify the required textboxes. I'm just not so keen on duplicating that line to all my form validations.

Upvotes: 0

Views: 1604

Answers (3)

Leon
Leon

Reputation: 149

Thanks everyone. Zachary's respond made me realise it's much easier than I thought. I ended up adding this overload:

(function($) {
    $.fn.extend({
        validateAndMarkRequired: function(options) {
            var validator = this.validate(options);
            this.markRequiredFields();
            return validator;
        }
    });
})(jQuery);

Upvotes: 0

bensiu
bensiu

Reputation: 25564

I would interfere with init method of validate plugin to execute your highlightRequiredFields plugin.

Do not forget to check is this plugin available, so validate would not break if uses without highlight somewhere else.

Upvotes: 1

Mark Pieszak - Trilon.io
Mark Pieszak - Trilon.io

Reputation: 66971

Why not simply do you're changes with CSS? I have a bunch of rules & even a few JS lines that run automatically on anything that has the class of required, and once they are valid / error, other things (that I want) happen to them.

Otherwise you'd have to most likely make changes inside of the $.fn.validate() plugin itself.

Upvotes: 1

Related Questions