【问题标题】:Validate a controlgroup with input of type="radio"使用 type="radio" 的输入验证控制组
【发布时间】:2013-05-17 11:50:49
【问题描述】:

我想验证一个具有输入为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");
            }
        });
    });

【问题讨论】:

    标签: html jquery-mobile jquery-validate jquery-mobile-fieldset jquery-mobile-radio


    【解决方案1】:

    解决方案 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/

    【讨论】:

    • 谢谢!有用。但是消息错误并没有以红色显示在字段下方...例如,对于控件组,它显示在上面,而对于输入文本和文本区域,它出现在里面,总是黑色的?我是否应该进行一些自定义以使错误消息显示如下:jquery4u.com/forms/basic-jquery-form-validation-tutorial
    • jQuery Mobile 验证的问题是 jQM 重新设置 HTML 内容样式后的 HTML 结构。因此,取决于小部件,错误不会总是显示在同一个地方。告诉我你希望它显示在哪里?
    • 我想在字段下方用红色显示错误消息。
    • 然后您需要创建自己的自定义,但请注意,需要一些代码才能使其正常工作。还是想让我教你怎么做?
    • 如果您指出一些基本示例,那就太好了。它可以是一个已经存在的例子,只是为了了解如何去做......
    猜你喜欢
    • 2021-10-10
    • 2014-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-08
    • 1970-01-01
    相关资源
    最近更新 更多