jQM - Validate jQuery Mobile radio

by Dragan Gaić

HTML

<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.10.0/jquery.validate.js"></script>
<!DOCTYPE html>
<html>
    <head>
        <title>jQM Complex Demo</title>
        <meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>
        <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; minimum-scale=1.0; user-scalable=no; target-densityDpi=device-dpi"/>
        <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css" />
        <script src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js"></script>    
    </head>
    <body>
        <div data-role="page" id="index">
            <div data-theme="b" data-role="header">
                <h1>Index page</h1>
            </div>
            
            <div data-role="content">
                <form id="sendMessageFormContainer" action="#">
                    <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 id="messageBox"></div>
                    </div>
                    <input id="sendMsgBtn" name="sendMsgBtnName" type="button" value="Send" />
                </form>
            </div>
        </div>    
    </body>
</html>

CSS

#messageBox li {
    background: red;
    color: white;
}

JavaScript

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