Friday, December 11, 2009

Showing image when validation fails using validation control

As they say .NET is a big ocean and each day you come across something new. Even after working for six years on .NET every other day I learn something new. One such experience I would like to share with this blog. In this blog we will see how to show an image when there is a validation error.

Anyone who is a ASP.NET developer would have used validation control at some point or the other. So with this blog I would like to show a small technique whereby you can show an image next to a control whenever a validation fails using a validation control. The great thing about this approach is that, it is in-built into all the validation controls and to do this one need not write any server side code or client side code. Just placing an image tag in the “ErrorMessage” property of the validation control will do. Lets see the code.

Required Numeric:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1"            ErrorMessage='<img src=images/error.gif />' Display="Dynamic"></asp:RequiredFieldValidator>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" CausesValidation="true" CommandName="Edit" />
<asp:Button ID="btnCancel" runat="server" Text="Cancel" CommandName="" CausesValidation="False"
            OnClick="btnCancel_Click" />

If you see the above code I have placed a html image tag in the “ErrorMessage” property of the required field validator control. So when you click the submit button without entering any value in “TextBox1” an error image will pop next to the textbox. The screenshot is shown below.

image

In the above image you can see an image, adjacent to the textbox, which was assigned to the “ErrorMessage” property of the validation control. In the above screenshot one thing which is missing is the description about the error. Wouldn’t it be nice to have a description about the error alongside the image? To achieve just that just place the error message before the html image tag as shown below.

<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1"           ErrorMessage="Required.<img src=images/imagesCAJD7BX6.jpg />" Display="Dynamic"></asp:RequiredFieldValidator>

From the above you can notice that we have inserted “Required.” text before the image tag. The output of this is pasted below.

image

Now we have a message alongside the image which gives as the detail of what went wrong. Now all this is fine, but some others would like to make use of the validation summary and show the error messages in the validation summary and error images along side the controls. Hmm, is that tricky? Not at all, its very easy. Lets see how?

Error image along with validation summary control

To show error image alongside the control and validation message in validation summary you have to make some small adjustments in the above code. First thing, obviously, is to insert a validation summary control. Next, Place the image tag in between the starting and ending tags of the validation control. I know you will be little confused, lets clear your confusion with some code. Here is what you need to do.

<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1"            ErrorMessage="Required." Display="Dynamic"><img src=images/imagesCAJD7BX6.jpg /></asp:RequiredFieldValidator>

In the above code I have purposefully not included the validation summary control. You can find the whole code at the end of the blog. If you notice, we have placed the image tag in between the starting and ending tag of the required field validator. Also we have the error message in the “ErrorMessage” property. The output of the above code is pasted below.

image

One thing to note here is that you have to set the “Display” property of the validation control to “Dynamic”.  If you set the “Display” property to “None”, which we usually use with validation summary control, then the image will not be displayed. So its very important to set the “Display” property to “Dynamic'” for this to work. The whole code along with the validation summary is pasted below.

<asp:ValidationSummary ID="ValidationSummary1" runat="server" />
Required Numeric:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1"            ErrorMessage="Required." Display="Dynamic"><img src=images/imagesCAJD7BX6.jpg /></asp:RequiredFieldValidator>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" CausesValidation="true" CommandName="Edit" />
<asp:Button ID="btnCancel" runat="server" Text="Cancel" CommandName="" CausesValidation="False"            OnClick="btnCancel_Click" />

Try to learn more

Sandeep

14 comments:

  1. Cool one man:):) your blog is of great help to ASP.net beginners like me:)

    ReplyDelete
  2. Hi Ajay,
    Thanks man for the feedback.

    ReplyDelete
  3. Thanks, just the answer I needed!

    ReplyDelete
  4. I am happy that you were able to find the answer what you wanted from my blog.

    ReplyDelete
  5. Nice blog,
    great info,
    but I needed to know, if i can place an image when its successfull (or true) so that theres an image of TICK for representing correct (or valid input),
    also retaining this above method if its wrong..
    so that,
    when i type wrong --> X (cross image)
    when i type correct --> (TICK image)
    (the above is validated once the submit button is activated)
    should i explain more or this is sufficient to get a solution

    ReplyDelete
  6. Hi,
    If you want to show an image when the validation is right then you need to handle the lostfocus event of the control and then get the ValidationControl associated with the control, check whether the validation is a success or not. If yes display the success (tick) image with the help of javascript. Other than this I don't think there is any other way.

    ReplyDelete
  7. thanks for reply, can you show a js code for an example ?

    ReplyDelete
  8. Hi,
    Sorry for the late reply, was held up with work. Below is the HTML and javascript code displaying an image when the validation is fine.

    <asp:ScriptManager ID="ScriptManager1" runat="server">
    <asp:TextBox ID="TextBox1" runat="server" onBlur="showImage()">
    <asp:RequiredFieldValidator ID="rfv" ControlToValidate="TextBox1" runat="server" Display="Dynamic" ErrorMessage="RequiredFieldValidator">
    <img id="img1" src="Images/Error.png" />
    <img style="visibility:hidden" id="imgCorrect" src="images/go.gif" />

    //Javascript code
    function showImage() {
    //Get the validation control.
    var valCntl = $get("<%= rfv.ClientID%>");
    //Call the ValidatorValidate javascript method to update the "isvalid" property.
    ValidatorValidate(valCntl);
    var img = $get("imgCorrect");
    //Validation is fine show the image.
    if (valCntl.isvalid)
    img.style.visibility = "visible";
    else
    img.style.visibility = "hidden";
    }

    ReplyDelete
    Replies
    1. sir your code will not execute because <asp:TextBox is a server side control and onBlur is javascript function and javascript will execute only on client side...

      Delete
    2. Thanks for codes. Working good but when even leaving textbox empty displaying image.

      Delete
  9. thanks for the reply, will check and revert back if success :D
    have a nice day

    ReplyDelete
  10. Nice article.Can i use the same method to get the error img for regular expression validation?.I tried,but the img is not showing.Any other method is there?

    Thanks in advance.

    ReplyDelete
  11. hai sandeep your bolg is vary helpfull for me.

    ReplyDelete
  12. Hi Rama,
    It' great to know that my blog helped.

    ReplyDelete

Please provide your valuable comments.