2

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 Answers 2

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.