Friday, January 20, 2012

Validation summary popup UI modification

In this post we will discuss how to modify the UI of validation summary with some CSS and jQuery.

Suppose we have two fields named first name and last name. And we need to implement required field validation. If we use RequiredFieldValidator and ValidationSummary with ShowMessageBox="true", then we can get the following result if we are not providing any value for the text fields-

Now we know that we cannot modify the message box UI. But if we want to do so-

If we change the ValidationSummary a little by ShowMessageBox="false" ShowSummary="true" DisplayMode="BulletList", then we get the following UI-

If we check the UI created for the summary we can find the following HTML generated-
    <div style="color: red" id="vsInfo" headertext="Following error occurs:" displaymode="BulletList">
        Following error occurs:
            <li>Provide first name</li>
            <li>Provide last name</li></ul>
What we can do is add a little trick here. We can use jQuery dialog to change the UI (I believe that we know how to use jQuery dialog. For reference check here).

The modified code goes here-
    <div id="dialog" style="display:none">
    <div class="itemContent">
        <div class="controls" style="display:none">
           <asp:ValidationSummary ID="vsInfo" runat="server" HeaderText="Following error occurs:"
                ShowMessageBox="false" ShowSummary="true" DisplayMode="BulletList"  />
    <script type="text/javascript">
        $(document).ready(function() {
            $("#btnSaveInfo").click(function() {
                document.TimeID = setTimeout("checkMessage()", 5);
        function checkMessage() {
            if ($("div#vsInfo").length > 0) {
                $("#dialog").append($("div#vsInfo UL"));
                    title: $("div#vsInfo").text(), 
                    close: function(event, ui) {
                document.TimeID = setTimeout("checkMessage()", 5);
What we are doing here is binding the click event to the save button, in the button click we are calling a function named checkMessage() periodically after every 5 milliseconds and checking whether a div with id vsInfo exists in the DOM. If exists, then copying the HTML of the ValidationSummary and putting it in the dialog div, opening the dialog and finally clearing the timer. So, final UI looks like-
That’s what we wanted. We can change the UI of the dialog as we need.

Download the code from here.

1 comment:

  1. Thanks...
    If not .length works, try this:

    if (!$.trim( $('div#vsInfo').is(':empty') ))