Compartilhar via


Adding messages to a Validation Summary

For a while now I’ve used this handy bit of code to add a message programmatically to a Validation Summary control, without associating it with a Validator. I’ve no idea where it came from – perhaps my head, perhaps someone cleverer than I... so if it was from you, shout up! I was asked how to do this today by a customer, so I felt inspired to blog it.

Anyway, sometimes you get an error from your business logic that it just isn’t practical to have pre-validated. For example, when adding a new employee to a database, perhaps the employee name has a UNIQUE constraint on it. Validating this up front might not be easy...

So if I get an error back from my business logic (either in the form of a list of validation errors, or in the worst case scenario as an exception) how do I display this message to the user? Well it turns out this is quite easy – just add a validator that is reporting itself as “IsValid = false” to the Page.Validators collection.

Consider the following class;

public class ValidationError : IValidator

{

    private ValidationError(string message)

    {

        ErrorMessage = message;

        IsValid = false;

    }

    public string ErrorMessage { get; set; }

    public bool IsValid { get; set; }

   

    public void Validate()

    {

        // no action required

    }

    public static void Display(string message)

    {

        Page currentPage = HttpContext.Current.Handler as Page;

        currentPage.Validators.Add(new ValidationError(message));

    }

}

(Note: This is using automatic properties - a C# 3.0 feature. Alter the code to use standard properties if you're using an earlier version of .NET)  

This immediately allows me to use the following code;

ValidationError.Display("Oops, some error occurred.");

 

Succinct, eh?! Here’s a shot of it in action;

 

Edit Employee Validatoin Error

Comments

  • Anonymous
    February 29, 2008
    Thanks for this. It definitely came in useful for me.

  • Anonymous
    March 28, 2008
    This works well - thanks for the tip.

  • Anonymous
    April 07, 2008
    Something similar to this can be done by adding a CustomValidator dynamically when the error occurs.  For example: CustomValidator cv = new CustomValidator(); cv.IsValid = false; cv.ErrorMessage = "The error to display."; this.Page.Validators.Add(cv);

  • Anonymous
    April 07, 2008
    The comment has been removed

  • Anonymous
    July 18, 2008
    Will this work with the AJAX UpdatePanel?  Where the whole page is not refreshed; will the validator make it onto the page?

  • Anonymous
    July 18, 2008
    @ Cory; Good question. I think the key will be whether or not the Validation Summary is inside the Update Panel or not - if it isn't it won't get refreshed... but if it is, it should work. Simon

  • Anonymous
    October 14, 2008
    How come it is not working when the validation summary's showmessagebox is true?

  • Anonymous
    October 15, 2008
    The comment has been removed

  • Anonymous
    January 16, 2009
    Pretty Cool...have you tried removing an error?  I thought maybe there was an items.clear or something similar [currentPage.Validators.Clear()], but no luck. Thanks

  • Anonymous
    January 18, 2009
    The comment has been removed

  • Anonymous
    February 28, 2010
    I was just looking for something like this! My best regards!

  • Anonymous
    May 25, 2010
    I used the code suggested by Nichole by it never causes any validation. Doesnt even stop page from being submitting. IOs there anything I am missing:- void PolicyStartDate_ValueChanged(object sender, EventArgs e)        {         if (PolicyStartDate != null)            {                if (DateTime.Parse(PolicyStartDate.Value.ToString()) < DateTime.Today)                {                 CustomValidator CustomValidatorCtrl = new CustomValidator();                    CustomValidatorCtrl.IsValid = false;                    CustomValidatorCtrl.ErrorMessage = "Please select correct policy start date";                    Page.Validators.Add(CustomValidatorCtrl);                  this.Page.Validate();                     }                else                {                                    }                }        } And my validation summary is in the update panel. Any suggestion?

  • Anonymous
    May 25, 2010
    @ Nisha, If you're just checking the date value against Today you could probably use another approach - perhaps a RangeValidator or a CustomValidator. The approach I've described here is mainly intended for validation that can only be done by comparing to database values, or perhaps that is performed by a web service that returns a list of errors etc. As for your code, apart from this I see nothing wrong with it - based on what you've provided. You shouldn't need to call this.Page.Validate() though. Have you wrapped your code that should run if validation succeeds with an "if (Page.IsValid)" too? I would finally point out that when you say "it doesn't even stop the page from submitting" that I'm assuming you realise this approach is a server-side only approach; it won't emit JavaScript to perform client-side validation (but using a RangeValidator would do!). Hope that helps, Simon

  • Anonymous
    September 22, 2010
    Hi Simon, I am using the below code. I want to display error message using MessageBox (ShowMessageBox="True"). MessageBox isn't popping up. Private Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click Dim blnFlag = callmethod() If Not blnFlag Then    Page.Validate()    ValidationError.Display("Place error message here") End If End Sub Public Class ValidationError    Implements IValidator    Private _errorMessage As String = String.Empty    Private _isValid As Boolean = False    Public Shared Sub Display(ByVal message As String)        Dim currentPage As Page = TryCast(HttpContext.Current.Handler, Page)        currentPage.Validators.Add(New ValidationError(message))    End Sub    Public Sub New(ByVal message As String)        ErrorMessage = message        IsValid = False    End Sub    Public Property ErrorMessage() As String Implements System.Web.UI.IValidator.ErrorMessage        Get            Return _errorMessage        End Get        Set(ByVal value As String)            _errorMessage = value        End Set    End Property    Public Property IsValid() As Boolean Implements System.Web.UI.IValidator.IsValid        Get            Return _isValid        End Get        Set(ByVal value As Boolean)            _isValid = value        End Set    End Property    Public Sub Validate() Implements System.Web.UI.IValidator.Validate    End Sub End Class Regards Janet

  • Anonymous
    September 22, 2010
    The comment has been removed

  • Anonymous
    September 22, 2010
    Simon,  How can i show MessageBox of Validation Summary from Code Behind. Regards Janet

  • Anonymous
    September 22, 2010
    Janet, I don't believe you can - it is just something the validation summary does automatically when that property is set, when a page is rendered. So you shouldn't need to - if you're doing a postback and rerender and have set the property I would expect it to have worked. Simon

  • Anonymous
    March 10, 2011
    Nice post. Solved one problem for me. Thanks.

  • Anonymous
    April 17, 2011
    Really helpful - saved me having to work out how to do it.  Thanks!  :-)