开发者

jQuery validate group 3 text inputs into one?

I have 3 text inputs for a phone number - phone_ac, phone_ex, phone_nm - i.e. 999 555 1212

I can use jquery to validate each individually and give 3 error messages:

"Phone number (area code) is required."
"Phone number (exchange) is required."
"Phone nu开发者_运维百科mber (last 4 digits) is required."

Is there a way to have one error message only if ANY of the 3 fields are blank?


I've previously handled similar situations by adding a hidden input named PhoneNumber and adding required and regex validation flags on it. Then prior to validating the form set its value to the concatenation of all three fields.


Set an errorContainer option with element that contains common error message and errorLabelContainer option and wrap the errorLabelContainer by unvisible container element.

   <style type="text/css">
       #errorMessage
       {
           display: none;
       }
   </style>

    <div style="display: none;">
        <div id="errorLabels" >
        </div>
    </div>
    <input type="text" id="phone_ac" class="required"  />
    <br />
    <input type="text" id="phone_ex" class="required" />
    <br />
    <input type="text" id="phone_nm" class="required" />
    <div id="errorMessage">
        All phone fields are required!</div>
    <hr />
    <input class="submit" type="submit" value="Submit" />


try like this

<script type="text/javascript">
        $(document).ready(function () {

            $('#stay-in-touch').validate({

                highlight: function (element, errorClass) {
                    $('#span1').text("Please enter all the values");
                },
                rules: {
                    text1: "required",
                    text2: "required",
                    text3: "required"
                },
                messages: {
                    text1: "",
                    text2: "",
                    text3: ""
                }
            });
        });


    </script>


    <form method="post" action="Default2.aspx" id="stay-in-touch" >
    <div>
        <input type="text" id="text1" name="text1" /> <br />              
        <input type="text" id="text2" name="text2" /> <span id="span1"></span> <br />              
        <input type="text" id="text3" name="text3" /> <br />   

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

    </div> 
    </form>   


There is a setting in jquery validate called 'groups' that does this. You can include it in your validate and group them by their ID's so if you have:

 <div>
    <input type="text" id="phone_ac" name="phone_ac" />              
    <input type="text" id="phone_ex" name="phone_ex" />              
    <input type="text" id="phone_nm" name="phone_nm" />   
</div> 

Try adding groups to you validate:

$('#yourform').validate({
//...Your existing validation logic...
groups: {
    phoneNumbers: "phone_ac phone_ex phone_nm"
}  
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜