Validation, Take Two

Make sure the only kind of information users enter is the kind you want them to enter.

asp.netNOW Q&A

LANGUAGES: C#

TECHNOLOGIES: Validation Controls | Regular Expressions

 

Validation, Take Two

Make sure the only kind of information users enter is the kind you want them to enter.

 

By Josef Finsel

 

Q. Is there a Validation control for .NET Web apps that will work with client-side locales to validate dates, times, and currencies? And is there way to write a regular expression that will validate dates of any form?

- R.G., Billerica, Mass.

 

A. The short answer for the first question is no; the longer answer requires some explanation. Validation controls in .NET are designed to make your life easier, but they do have some limitations. Let's take a quick look at the RequiredFieldValidator to see how Validators work.

 

I'll create a simple login page with a textbox for a userid and a Submit button. Next, I'll add a RequiredFieldValidator control for the userid and set the ControlToValidate property to the userid textbox. Once I've built the project I can load it in a browser, and when I click on the Submit button I'll get an error. The question is, where is the error being processed? The answer is: It depends.

 

If I open the page using Internet Explorer, the source code rendered to the browser is quite different than when I open it using Mozilla. In Mozilla, the page is rendered as minimal HTML and the validation is completed on the server side. Within IE, however, an additional script is loaded (you can find a copy on your Web server in the WebUIValidation.js file's /aspnet_client/system_web/ver/ directory). In addition, the IE version contains JavaScript code to invoke the client-side validation.

 

If the Submit button  is hit on the IE client, it will continue to do the validation on the client until it is correct without making another trip to the server. If your .NET Web server doesn't know your client can handle the client-side scripting, every press of the Submit button will cause your server to process the validation. This actually is how validation was done before ASP.NET, but it required coding the client-side scripting then writing the server-side checks to act as a belt to the server-side suspenders. With ASP.NET, validation is handled automatically unless, of course, you want to do specific client-side validation such as checking for local time and local currency settings. In these, instances you still need to write client-side code to implement that functionality.

 

Which brings me to the second question: How do you use a regular expression to parse the date? This regular expression will take care of the date format:

 

^\d{1,2}\/\d{1,2}\/\d{4}$

 

This only verifies, however, the MM/DD/YYYY format; it does nothing to verify whether a date, such as 42/12/0923, is valid. To handle this, you need to use a much more complicated string:

 

^(?:(?:(?:0?[13578]|1[02])(\/|-|\.)31)\1|(?:(?:0?[1,3-9]|1[0-2])(\/|-|\.)(?:29|30)\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:0?2(\/|-|\.)29\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:(?:0?[1-9])|(?:1[0-2]))(\/|-|\.)(?:0?[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$

 

This string verifies a U.S. date format for 1/1/1600 to 12/31/9999. Again, depending on the browser, the validation could take place either on the server or the client. Fortunately, you don't have to build these expressions yourself. You'll find a library of regular expressions you can use at http://www.regexlib.com. This site includes the more sophisticated date-checker I mentioned previously, and it contains versions for other nationalities as well.

 

Q. How do I use a validation control to specify that a textbox must contain five to eight characters, for example, in a password entry?

- H.W., Queensland, Australia

 

A. This is handled best by using a CustomValidatorControl. Although all the other Validator controls have built-in functionality, this custom Validator lets you make up the rules as you go along. Unlike the other Validators, however, the custom Validator requires some additional programming. First, you need the code that the Validator control runs. Double-click on the Validator to open the source code. The key is setting the args.IsValid - set it to true if everything is valid and false if it isn't. This simple example checks for the length of the password field:

 

private void CustomValidator1_ServerValidate(object source, System.Web.UI.WebControls.ServerValidateEventArgs args)

{

   if (txtPass.Text.Length>=5 && txtPass.Text.Length<=8)

  {args.IsValid=true;}

   else

            {args.IsValid=false;}

}

 

Once you've written the Validator code, you need to write the code to invoke it. To do this, you need to check the Page.IsValid property. Here, every time the Submit button  is pressed, a trip to the server is required to validate the code:

 

private void Button1_Click(object sender, System.EventArgs e)

    {

      if (Page.IsValid)

      { lblValid.Text = "Valid Password";}

      else

      { lblValid.Text = "";}

    }

 

But you don't have to do it this way. Instead, you can use ClientValidationFunction, a property of CustomValidatorControl. If you have written client-side code that does the custom validation, you can name it in this property and avoid having the server validate the data. The downside to creating client-side custom validation code is that you must maintain two sets of code in case someone is using a browser that doesn't support your validation code.

 

The code referenced in this article is available for download.

 

Have a question? Send it to [email protected].

 

Josef Finsel is a software consultant with G.A. Sullivan, specializing in .NET and SQL Server. He has published a number of VB, .NET, and SQL Server-related articles and, when he isn't hanging around the aspenetpro forums, you can find him working on the syntax for FizzBin.NET, a programming language that works the way programmers have always suspected. He's also author of The Handbook for Reluctant Database Administrators.

 

 

 

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