views:

57

answers:

2

Hi

I want to write a custom validator which doesn't do anything before the user makes a post back (i.e. no JavaScript will be generated for it). The validator should make sure that there is a POST argument with the name hello. The value of that argument must be a comma-separated string of integers.

The reason that I want to make this an actual validator is that I want to integrate the error message into the validation summary that I'm using, which displays a bulleted list of errors.

So where do I start?

+2  A: 

First, add a custom validator control to the page

<asp:CustomValidator ID="MyValidator" runat="server" ErrorMessage="My error message" 
    OnServerValidate="MyValidator_OnServerValidate" />

Then in your codebehind add the MyValidator_OnServerValidate method.

protected void MyValidator_OnServerValidate(object sender, ServerValidateEventArgs e)
{
      e.IsValid = false;

      // Validation logic goes here
      if(Request.Form["hello"] == null)
          return;

      ...

      // If we have made it this far, then everything is valid
      e.IsValid = true;
}
Mike J
A: 

The validation summary works with client side errors too. That is, you DONT have to postback to get the validation summary to display a new error. In fact, as a strategy, I would recommend having client script AS WELL as server side checks where possible. At the very least - when enabled - the client checking can help reduce network chatiness, server resources and improve the user experience.

brumScouse
It was a while since I asked this question, but I think the reason I said that I only wanted server-side validation was that I had a hard time understanding custom validators at all and it would be a tad simpler to explain how they work if it was supposed to be server-side only. I don't remember to be honest.
Deniz Dogan