Trick to place jQuery Validation Error


Sunday, October 31, 2010

In this post, i will show you, how to place jQuery error where you like.

By default, when you use jquery validation function, then error get placed below the control for which you are validating.

But sometime, situation arise, you want jQuery error to be shown someother place for that control, so in that condition, you can use below trick and place error, where you like.

To do this,

You have to declare jquery files in your Page Head Tag, as shown below.


<script type="text/javascript" src="../resources/js/jQuery/jquery-1.4.3.min.js"></script>
<script type="text/javascript" src="../resources/js/jQuery/jquery.validate.js"></script>



After declareing files, just use below code to validate the control


        <script type="text/javascript">
            $(document).ready(function() {
                $("#frmPEOfficeCreation").validate({
                    rules: {
                        txtdepartment: { required: true }
                    },
                    messages: {
                        txtdepartment: { required: "<br/>Please select department" }
            }
                });
            });
        </script>


You can see below Image as output, where you can see, the error is shown after "new window" button, that is not looking good and not correct with respect to layout.



so Now what you can do is,you can make use of errorplaceholder function avalible in jQuery, LIke i have done below


<script type="text/javascript">
            $(document).ready(function() {
                $("#frmPEOfficeCreation").validate({
                    rules: {
                        txtdepartment: { required: true }
                    },
                    messages: {
                        txtdepartment: { required: "<br/>Please select department" }
            },
                    errorPlacement: function(error, element) {
                        if (element.attr("name") == "txtdepartment")
                            error.insertAfter("#btnnewbutton");
                        else
                            error.insertAfter(element);
                    }
                });
            });
        </script>


Then you can see correct layout, shown below in image



Hope this post will help you,
if yes please put comment below of this page,
Rajesh Singh,
Senior Asp.Net Developer

Email: raj143svmit@gmail.com
e-Procurement Technologies Ltd (India)
www.abcprocure.com

No comments :