使用jquery验证插件验证多选

时间:2012-04-19 10:11:22

标签: jquery widget jquery-validate multi-select

试图找出我的收件人multiselect未在表单提交时验证的原因。应至少选择1人。我将它设置为必需的但仍然没有显示错误。

http://jsfiddle.net/mMZYT/

JS:

var validateform = $("#pmForm").validate({
    rules: {
        recipient: {
            required: true
        },
        bcc: {
            required: true
        },
        subject: {
            required: true
        },
        message: {
            required: true
        }
    },
    invalidHandler: function(form, validator) {
        var errors = validator.numberOfInvalids();
        if (errors) {
            var message = errors == 1
            ? 'You missed 1 field. It has been highlighted.'
            : 'You missed ' + errors + ' fields. They have been highlighted.';
            $('.box .content-form').removeAlertBoxes();
            $('.box .content-form').alertBox(message, {type: 'warning', icon: true, noMargin: false});
            $('.box .content-form .alert').css({
                width: '',
                margin: '0',
                borderLeft: 'none',
                borderRight: 'none',
                borderRadius: 0
            });
        } else {
            $('.box .content-form').removeAlertBoxes();
        }
    },
    showErrors : function(errorMap, errorList) {
        this.defaultShowErrors();
        var self = this;
        $.each(errorList, function() {
            var $input = $(this.element);
            var $label = $input.parent().find('label.error').hide();
            $label.addClass('red');
            $label.css('width', '');
            $input.trigger('labeled');
            $label.fadeIn();
        });
    },
    submitHandler: function(form) {
        var dataString = $('#pmForm').serialize();
        $.ajax({
            type: 'POST',
            url: 'http://www.kansasoutlawwrestling.com/kowmanager/pmsystem/pmsubmit',
            data: dataString,
            dataType: 'json',
            success:  function(data) {
                if (data.error) {
                    $('.box .content').removeAlertBoxes();
                    $('.box .content').alertBox(data.message, {type: 'warning', icon: true, noMargin: false});
                    $('.box .content .alert').css({
                        width: '',
                        margin: '0',
                        borderLeft: 'none',
                        borderRight: 'none',
                        borderRadius: 0
                    });
                }
                else
                {
                    $('.box .content').removeAlertBoxes();
                    $('.box .content').alertBox(data.message, {type: 'success', icon: true, noMargin: false});
                    $('.box .content .alert').css({
                        width: '',
                        margin: '0',
                        borderLeft: 'none',
                        borderRight: 'none',
                        borderRadius: 0
                    }); 
                    $(':input','#pmForm')
                    .not(':submit, :button, :hidden, :reset')
                    .val('');  
                }
            }
        });
    }
});

有什么想法吗?

2 个答案:

答案 0 :(得分:9)

您可以使用以下代码验证所需的单一选择。

魔术发生在这一行:

ignore: ':hidden:not("#mySelect")'

这是必要的,因为默认情况下jQuery Validate会忽略隐藏字段......

<强> HTML

<form action="some/action" id="myForm" method="POST">

    Select: <select class="someSelect" name="mySelect" id="mySelect" multiple="multiple">
        <option value="some_val1">Some Value</option>
        <option value="some_val2">Some Other Value</option>
    </select>

    <input type="submit" value="Submit" />

</form>

<强>使用Javascript / jQuery的

$(document).ready(function() {
    $('#mySelect').multiselect({
        noneSelectedText: 'Select Something (required)',
        selectedList: 3,
        classes: 'my-select'
    });

    $.validator.addMethod("needsSelection", function(value, element) {
        return $(element).multiselect("getChecked").length > 0;
    });

    $.validator.messages.needsSelection = 'You gotta pick something.';

    $('#myForm').validate({
    rules: {
        mySelect: "required needsSelection",
        input1: "required isPercent",
        input2: "required",
        input3: "required"
    },
    ignore: ':hidden:not("#mySelect")', // Tells the validator to check the hidden select
    errorClass: 'invalid'
    });
});

答案 1 :(得分:2)

接受的答案不再适用。问题是"getChecked"论证不再做任何事了。以下是验证方法

的更新工作版本
$.validator.addMethod("needsSelection", function (value, element) {
                var count = $(element).find('option:selected').length;
                return count > 0;
            })