Validate a controlgroup with input of type="radio"

4.7k views Asked by At

I want to validate a form that have a controlgroup with inputs of type="radio" like this:

<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>

I'm using validate() method to validate the rest of the elements, but I don't know which rule should I use to check that at least one radio button should be selected:

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

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

There are 1 answers

6
Gajotres On BEST ANSWER

Solution 1

You need to add at least one class="required" to anyone of your radio inputs, like this:

<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>

Working example: http://jsfiddle.net/Gajotres/a8cJA/

Solution 2

Or you can do it like this:

$(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();
    });    
});

Working example: http://jsfiddle.net/Gajotres/HwQeY/