Validating multiple select boxes with the jQuery Validation Plugin

混江龙づ霸主 提交于 2019-12-14 01:27:14

问题


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:


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/



来源:https://stackoverflow.com/questions/13921701/validating-multiple-select-boxes-with-the-jquery-validation-plugin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!