Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating multiple select boxes with the jQuery Validation Plugin

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.

like image 631
SeanWM Avatar asked Aug 07 '26 10:08

SeanWM


1 Answers

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/

like image 173
Andrew Whitaker Avatar answered Aug 10 '26 06:08

Andrew Whitaker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!