1

我想验证一个具有控制组的表单,其输入type="radio"如下:

<form id="sendMessageFormContainer" action="#">
    @Html.ValidationSummary()
    <div data-role="fieldcontain">
        <fieldset data-role="controlgroup">
            <legend>To:</legend>
            <div id="messageToContainer">
                 <input type="radio" name="radio-choice-1" id="radio-choice-1" value="1" />
                 <label for="radio-choice-1">foo</label>
                 <input type="radio" name="radio-choice-1" id="radio-choice-2" value="2" />
                 <label for="radio-choice-2">bar</label>
            </div>
        </fieldset>
    </div>

//...

    <input id="sendMsgBtn" name="sendMsgBtnName" type="submit" value="Send" />
</form>

我正在使用validate()方法来验证其余元素,但我不知道应该使用哪个规则来检查是否应该选择至少一个单选按钮:

$(document).on("pageshow", function () {

        $("#sendMessageFormContainer").validate({
            rules: {
                //???
            },
            messages: {
                //...
            },
            submitHandler: function (form) {
                alert("Call Send Action");
            }
        });
    });
4

1 回答 1

2

解决方案 1

您需要为任何无线电输入添加至少一个 class="required",如下所示:

<input type="radio" name="radio-choice-1" id="radio-choice-1" value="1" class="required" />
<label for="radio-choice-1">foo</label>
<input type="radio" name="radio-choice-1" id="radio-choice-2" value="2" />
<label for="radio-choice-2">bar</label>

工作示例:http: //jsfiddle.net/Gajotres/a8cJA/

解决方案 2

或者你可以这样做:

$(document).on('pagebeforeshow', '#index', function(){ 
    $("#sendMessageFormContainer").validate({
        rules : {
            "radio-choice-1" : { required : true }
        },
        messages : {
            "radio-choice-1" : "Please select radio button"
        },
        submitHandler: function (form) {
            alert("Call Send Action");
        }
    });    
    $(document).on('click', '#sendMsgBtn', function(){ 
        $("#sendMessageFormContainer").validate().form();
    });    
});

工作示例:http: //jsfiddle.net/Gajotres/HwQeY/

于 2013-05-17T11:55:40.933 回答