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 (19)

  1. Jason says:

    Thanks for this. It definitely came in useful for me.

  2. KA says:

    This works well – thanks for the tip.

  3. Nicole says:

    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.";


  4. Simon J Ince says:


    Very true, I like it. You could easily wrap this up in a static helper method similar to my approach above.

    I guess the advantage with your approach is that there is less custom code – if the IValidator interface changed or the internal behaviour of validation changed using the out-of-the-box CustomValidator is less likely to break. Perhaps a little bit theoretical, but I’m all for minimising the code I write so sounds like a good excuse to me!!

    Good stuff.


  5. Cory says:

    Will this work with the AJAX UpdatePanel?  Where the whole page is not refreshed; will the validator make it onto the page?

  6. Simon J Ince says:

    @ 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.


  7. @sg says:

    How come it is not working when the validation summary’s showmessagebox is true?

  8. Simon J Ince says:


    I think you’d need to implement a JavaScript validation function for this to work. Check out the docs on CustomValidator.ClientValidationFunction;

    The behaviour you’re seeing is the same as if you set EnableClientScript to false on a RequiredFieldValidator, for example.

    Of course, the problem is this approach is designed to work with scenarios when you need server-side validation so it isn’t an ideal fit. I must admit I never use the message box option as I think users sometimes find it intrusive, so I guess that’s why it has never been a problem for me.

    Hope that helps!


  9. Mike says:

    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.


  10. Simon J Ince says:

    @ Mike;

    I think the Validators collection is deliberatley read only… but I wonder if you could call "Page.Validate()" again, assuming you’ve altered your custom validator to return "IsValid=true". This should mean it drops off the list.

    It is possible that disabling out-of-the-box validators and then re-validating the page might have a similar effect, but I’ve never tried it.

    As far as I know, there’s no way to remove individual validation errors once the page has been validated.

    If you try any of these theories do report back and let us know if you had any luck!


  11. Rafael Meneses says:

    I was just looking for something like this! My best regards!

  12. Nisha yadav says:

    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";









    And my validation summary is in the update panel.

    Any suggestion?

  13. Simon J Ince says:

    @ 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,


  14. Janet says:

    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


       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


               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


               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



  15. Simon J Ince says:

    Hi Janet,

    I can't see anything immediately wrong with your code – just check that you haven't renamed anything that's caused it to break. The other thing to check is that I believe the message box functionality is part of the validation summary control, so it might not be related to this code – are all javascript files loading into the page correctly etc?

    I have heard (maybe even seen myself) of similar issues in the past but it's been so long I don't remember how I fixed them – there are quite a few articles online covering it though, so one of those might sort you out. For example;…/482619.aspx


  16. Janet says:


     How can i show MessageBox of Validation Summary from Code Behind.



  17. Simon J Ince says:


    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.


  18. Feng Chen says:

    Nice post. Solved one problem for me. Thanks.

  19. Barry Clark says:

    Really helpful – saved me having to work out how to do it.  Thanks!  🙂

Skip to main content