Validation

Team Fly 

Page 282

            ListBox1.DataSource = MyArray
            ListBox1.DataBind()

        Else ' it is a postback, so process the user's click
            Response.Write(''You clicked: " & ListBox1.SelectedItem.Text)
        End If

    End Sub

Here you only need to fill this ListBox the first time you send the page to the user. So If Not IsPostBack Then makes this decision. If the user is sending a postback, the ListBox remains filled, but now you have to react to the user's click.

Validation

Users have been known to enter all kinds of wrong input, including zip codes for area codes, their date of birth in reverse Polish notation, and their mother's maiden name for their favorite pet. There's not much you can do to detect that last one—pet names cannot easily be distinguished from maiden names—but most user input can be screened before adding it to a database or using it to fulfill a catalog order.

If they're ordering a shirt and they type in 125 as their neck size, you can politely request that they revise this measurement. If they type in nine digits for an area code, you can respectfully suggest that they try, try again.

You can validate user input either programmatically or via the new .NET validation controls, as described in the following sections.

Programmatic Validation

There are various ways to programmatically validate user entries, but one of the most useful involves Regex, a complex language for various kinds of text management. In general, you don't want drive yourself barmy by trying to construct regular expressions yourself—there's nothing regular about them.

However, they can come in handy, so to use them just locate libraries of pre-written expressions on the Internet, or examples in VB.NET Help. I located the following mind-bender in Help. It determines whether or not a string is a valid e-mail address. Here's what it looks like:

 "^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-" Z]{2,4}|[0-9]{1,3})(\]?)$ 

See what I mean?

This next example illustrates another way to interact with the user via the middle tier. Add Imports System.Text.RegularExpressions to the code window. Put a button and a TextBox on a WebForm. The user enters an e-mail address in the TextBox, then clicks the button. Change the Text properties of these controls so they look like this:

 TextBox1.Text = "Please enter your email address..." Button1.Text = "Click to validate" 

Then type Listing 11.5 into the button's Click event.

Team Fly 


Visual Basic  .NET Power Tools
Visual Basic .NET Power Tools
ISBN: 0782142427
EAN: 2147483647
Year: 2003
Pages: 178

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net