3

So I've run into a bit of an issue while working with the jQuery Validation Plugin. I have 3 select tags next to each other so a user can enter their birthday. How do I go about having 1 validation message for 3 select tags? I've heard maybe a custom rule can be done?

Here's the HTML and I've included a jsfiddle.

<form id="commentForm" action="" method="post">
<p>
    <label for="month">Birthday:</label>
    <select name="month" class="required select">
        <option value="">Month</option>
        <option>Jan</option>
        <option>Feb</option>
    </select>
    <select name="day" class="required select">
        <option value="">Day</option>
        <option>01</option>
        <option>02</option>
    </select>
    <select name="year" class="required select">
        <option value="">Year</option>
        <option>1990</option>
        <option>1991</option>
    </select>
</p>
<input type="submit" value="Sign Up" class="button">
</form>​

This is an example of what's currently going on.

Thanks in advance.

1 Answer 1

4

You can use the group option to group together fields so that one error message is shown for the group. You can then place that one error message where you desire using the errorPlacement option:

$("#commentForm").validate({
    groups: {
        birthday: "month day year"
    },
    errorPlacement: function(error, element) {
        var name = element.prop("name");
        if (name === "month" || name === "day" || name === "year") {
            error.insertAfter("select[name='year']");
        } else {
            error.insertAfter(element);
        }
    }
});

Example: http://jsfiddle.net/atLV4/3/

Sign up to request clarification or add additional context in comments.

4 Comments

+1, nice answer, can you set a custom message like These fields are required ?
@SheikhHeera: Thanks! Yep, you would populate the messages option that you can supply to validate. You'd have to provide an error message for each field within the group though.
Thanks a lot. It worked great! Apparently copying the js from jsfiddle causes a Syntax Error: illegal character sometimes. Took me forever to fix that. Just had to type the whole thing by hand.
@Sean: Glad to help! Sorry about the illegal character issue, it is annoying

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.