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