2

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">

2 Answers 2

3

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);
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

-2

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

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.