Skip navigation

Everyone Needs to Be Validated

Save time and effort by using ASP.NET’s CustomValidator class.

Hot Tip

LANGUAGES: C#

TECHNOLOGIES: Validation Controls

 

Everyone Needs to Be Validated

Save time and effort by using ASP.NET's CustomValidator class.

 

By Jeff Prosise

 

I frequently run across people who want to use ASP.NET's validation controls to check on something very specific - such as verifying an expression entered into a TextBox is numeric and a multiple of 10. They can't find an existing validation controls that fits the bill, and want to know whether they need to write a custom validator.

 

The fact is,   rather than write a custom validator of your own, you can save time by using ASP.NET's CustomValidator class, which validates input using an algorithm you supply. The page in Figure 1 uses a CustomValidator to reject anything other than a multiple of 10. The validator performs its checking on the server side as well as the client side, which prevents spoofing and ensures the input is checked even if it comes from a down-level browser (or a browser in which JavaScript is turned off).

 

<html>

  <body>

    <form runat="server">

      <asp:Button Text="Test" RunAt="server" />

      <asp:TextBox ID="Input" RunAt="server" />

      <asp:CustomValidator ControlToValidate="Input"

        ClientValidationFunction="__validateInput"

        OnServerValidate="ValidateInput"

        ErrorMessage="Must be a multiple of 10"

        Display="static" RunAt="server" />

    </form>

  </body>

</html>

 

<script language="JavaScript">

<!--

function __validateInput (source, args)

{

    args.IsValid = (args.Value % 10 == 0);

}

-->

</script>

 

<script language="C#" runat="server">

void ValidateInput (Object sender,

    ServerValidateEventArgs e)

{

    try {

        e.IsValid = (Convert.ToInt32 (e.Value) % 10 == 0);

    }

    catch (FormatException) {

        e.IsValid = false;

     }

}

</script>

Figure 1. CustomValidator controls validate input using algorithms you supply. The one in this page ensures that a value typed into a TextBox is numeric and is a multiple of 10.

 

Jeff Prosise is author of several books, including Programming Microsoft .NET (Microsoft Press). He also is a co-founder of Wintellect (http://www.wintellect.com), a software consulting and education firm that specializes in .NET. Got a question for this column? Submit queries to [email protected].

 

 

 

 

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish