Add text to asp:ValidationSummary (C#)

This trick is especially useful when you have custom code to be executed after your form have been submitted, and still wishes to communicate an error the same way as you communicate form validation errors.

Imagine the following ValidationSummary:

<asp:ValidationSummary ID="valSummary" 
  runat="server" 
  DisplayMode="BulletList" 
  ValidationGroup="ValGroup" 
/>

Any form error is displayed in this summary. When the user clicks your submit button you process the form:

protected void btnSubmit_Click(object sender, EventArgs e)
{
  Page.Validate();
  if (Page.IsValid)
  {
    // do custom processing of form
  }
}

But is the processing fails, is it too late to pop the validation summary? Not at all.
To do so, add a CustomValidator to your form:

<asp:CustomValidator 
  ID="valCustom" 
  runat="server" 
  ValidationGroup="ValGroup" 
/>

And simply set the error message in the CustomValidator, inside your btnSubmit_Click:

protected void btnSubmit_Click(object sender, EventArgs e)
{
  Page.Validate();
  if (Page.IsValid)
  {
    bool isOK = ProcessTheFormData();
    if (!isOK)
    {
      // Optional: Update the summary with a nice header
      valSummary.HeaderText = "Oops something went wrong";

      // Mandatory: Invalidate the custom validator, and set a error message
      valCustom.IsValid = false;
      valCustom.ErrorMessage = "A clever error message";
    }
  }
}

 

 

 

Advertisements

About briancaos

Developer at Pentia A/S since 2003. Have developed Web Applications using Sitecore Since Sitecore 4.1.
This entry was posted in c#, General .NET and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s