WebMasterSam

.Net, SEO, Dynamics CRM, AdSense/AdWords, Dating sites, Silverlight, Web hosting and more

About me

I'm an IT consultant working primarily with the .Net Framework as a developper and architect. I also work on my own on my personnal dating websites. I've been developping websites since 2000.

If you like what I do, feel free to support me

PayPal - The safer, easier way to pay online!

Bookmark

Bookmark and Share

Last comments

None

Adding custom error message to ValidationSummary without validators

Validators are a great thing in the ASP.Net world (as well as the .Net WinForms world...), but sometimes they don't suffice. For example, if you want to validate something not related to a control on the page or something very complex you can't achieve even with the custom validators, you may want a particular solution like this one.

First approach : using the CustomValidator

With this approach you simply have to do the following piece of code when you want to add a custom message to your validator :


CustomValidator val = new CustomValidator();

val.IsValid = false;
val.ErrorMessage = "Custom error message to add to the ValidationSummary";

this.Page.Validators.Add(val);

This is a cool, clean and simple way to add custom error messages to the ValidationSummary.

Second approach : creating a validator by implementing IValidator

The .Net framework allows you to create very custom validator by implementing the IValidator interface. So you create the validator and then use the same technique I've just showed you before, just like this :


public class ValidationError : IValidator
{
    private ValidationError(string message)
    {
        this.ErrorMessage = message;
    }

    public void Validate()
    {
        this.IsValid = false;
    }
}

this.Page.Validators.Add(new ValidationError("Your custom error message"));

Personnaly I prefer this one because you are completely custom and you can add messages in a single line of code.

Posted: Jul 03 2009, 15:15 by WebMasterSam | Comments (0) RSS comment feed |
  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Filed under: .Net | Programming
Social Bookmarks: E-mail | Kick it! | DZone it! | del.icio.us
LINK BUILDING IS PROHIBITED ON THIS WEBSITE