Alex
Alex

Reputation: 349

jQuery validate group validation

I'm using jQuery validate plugin. I have 3 fields, and need to validate them only if one of them is not empty, otherwise do not validate at all.

<input type="text" data-validate="{validate:{required:true, 
messages:{required:'Flickr set is required'}}}" id="flickr_set" name="flickr_set">


<input type="text" data-validate="{validate:{required:true, 
messages:{required:'Flickr ID is required'}}}" id="flickr_id" name="flickr_id">

<input type="text" data-validate="{validate:{required:true,
positiveNumber:true, messages:{required:'Photos count is required',
positiveNumber:'Positive number is required'}}}" id="flickr_photos-count" name="flickr_photos-count">

Upvotes: 2

Views: 2153

Answers (2)

Jeff Wilbert
Jeff Wilbert

Reputation: 4520

You need to use the dependency-callback method of the validation plugin.

What this will allow you to do is:

Makes the element required, depending on the result of the given callback.

You can then place a required validation rule on the 3 fields that says this field will only be required based on the return from the function callback; you can then put a rule on the fields to say require this field if any of the fields are not blank return true, or don't require this field if all the fields are blank return false

Thus if any of the fields are filled in they all become required, if they're all left empty none of them are required.

rules: {
    flickr_set: {
        required: function(element) {
            return ($("#flickr_set").is(':empty') && $("#flickr_id").is(':empty') && $("#flickr_photos-count").is(':empty') ? false : true);
        }
    },
    flickr_id: {
        required: function(element) {
            return ($("#flickr_set").is(':empty') && $("#flickr_id").is(':empty') && $("#flickr_photos-count").is(':empty') ? false : true);
        }
    },
    flickr_photos-count: {
        required: function(element) {
            return ($("#flickr_set").is(':empty') && $("#flickr_id").is(':empty') && $("#flickr_photos-count").is(':empty') ? false : true);
        }
    }
}

Upvotes: 3

Niels
Niels

Reputation: 49919

Just da a

$("form").validate();

And give the input fields a class required.

If you want to have custom messages you can change above javascript to:

$("form").validate({
    messages : {
        flickr_set : "Flickr set is required",
        flickr_id : "Flickr ID",
        flickr_photos-count : "Photos count is required"
    }
});

Upvotes: -2

Related Questions