简体   繁体   中英

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.

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM