Welcome to MSDN Blogs Sign in | Join | Help

Simon Ince's Blog

Ramblings of an Application Development Consultant in the UK
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

Posted: Thursday, February 28, 2008 8:21 PM by simonince
Filed under: ,

Comments

Jason said:

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

# February 29, 2008 12:07 PM

KA said:

This works well - thanks for the tip.

# March 28, 2008 1:15 PM

Nicole said:

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

# April 7, 2008 2:06 PM

simonince said:

Nicole;

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.

Simon

# April 8, 2008 5:13 AM

Cory said:

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

# July 18, 2008 12:27 PM

simonince said:

@ 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

# July 18, 2008 12:36 PM

@sg said:

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

# October 15, 2008 1:17 AM

simonince said:

@sg;

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

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.customvalidator.clientvalidationfunction.aspx

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!

Simon

# October 16, 2008 6:34 AM

Mike said:

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

# January 16, 2009 6:33 PM

simonince said:

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

Simon

# January 19, 2009 3:34 AM
Leave a Comment

(required) 

(required) 

(optional)

(required) 

  
Enter Code Here: Required

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Page view tracker