开发者

ASP.NET: Writing a custom server-side-only validator

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?


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;
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜