Custom Validator Error from Server Side

The built in ASP.NET validators are amazing as we all know. You just drag them on the page, tell them what control to validate, give them a summary control to list the errors and they do it. But what if there's something you need to add server side? Such as something that needs to check with the database before saving. You already have your validation summary control, so it would be nice to re-user that and have everything automatically looking the same. But it would appear there's no easy way of doing it built in, so here's an easy way of doing it... 

Creating a Custom Validation Error

First your going to need a class with some static class's that you can pass your error message to. Here I have two functions one for simply adding the error to the page and the other for adding the error to the page with a specific validation group. I am using a CustomValidator object to make this all work, another option is to implement IValidator but it's actually more effort than's needed. The other section to note is that I'm setting the Error.Text to a non breaking space (this is what would normally go next to the form field you're validating). This is because if you don't then it will default to the ErrorMessage which we only want to go into the summary. If you try setting it to a normal space it will still also default to the summary text.

1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Web;
5using System.Web.UI;
6using System.Web.UI.WebControls;
7
8/// <summary>
9/// Summary description for Validator
10/// </summary>
11public class ValidationError
12{
13
14 public static void Display(string Message)
15 {
16 Display(Message, "");
17 }
18
19public static void Display(string Message, string ValidationGroup)
20 {
21CustomValidator Error = new CustomValidator();
22 Error.IsValid = false;
23 Error.ErrorMessage = Message;
24 Error.ValidationGroup = ValidationGroup;
25 Error.Text = " ";
26
27Page currentPage = HttpContext.Current.Handler as Page;
28 currentPage.Validators.Add(Error);
29 }
30}

Now to trigger the error you just need to called the function as below:

1ValidationError.Display("Useful error message", "ValidationGroupName");