ControlFreak

LANGUAGES: VB.NET | C#

ASP.NET VERSIONS: 2.x | 3.x

 

Terrific TextBoxes

Teach Your TextBoxes a Few New Tricks

 

By Steve C. Orr

 

The standard ASP.NET TextBox is sturdy, proven, and reliable. Yet, it s difficult to find reasons to get excited about this relatively utilitarian control until now! The free, open source AJAX Control Toolkit provides several extenders that can turbo charge your TextBoxes with enhanced functionality (see Figure 1).

 

Control Name

Description

TextBoxWatermark

This extender saves space on the screen by internally labeling text boxes with a watermark effect.

FilteredTextBox

An extender that permits only certain types of characters to be entered into an associated text box, such as numbers or lowercase characters only.

MaskedEdit

This extender ensures a user s text box input matches a specified pattern, such as date or currency.

MaskedEditValidator

A custom validator that works with the MaskedEdit extender to help ensure users input correctly formatted values.

Figure 1: The AJAX Control Toolkit includes several useful extenders to enhance TextBoxes with exciting new functionality.

 

The simple TextBoxWatermark extender is a great way to conserve screen real estate by condensing labels and other descriptive text. The FilteredTextBox and MaskedEdit extenders are two great ways to foolproof user input and enhance usability. The MaskedEditValidator works flawlessly with the MaskedEdit extender to provide enhanced validation possibilities. Now let s take a look at each of these extenders in more detail.

 

The AJAX Control Toolkit

If you ve upgraded to Visual Studio 2008, you ll be pleased to discover that the AJAX Control Toolkit is easier than ever to work with. It includes more than 30 free and useful controls that integrate smoothly with your development environment. These development controls even with their complete source code, sample pages, and documentation are less than 3 megabytes in download size.

 

The well written source code is a fantastic resource for learning how to develop cutting-edge Web controls that leverage Microsoft s new AJAX client-side library.

 

To provide a rough idea of the complexity of the code, the relatively boilerplate server-side C# code for a simple control such as the TextBoxWatermark control is only 90 lines (including comments and white space). The client-side JavaScript code for this same control is 360 lines. Conversely, some of the more complex toolkit controls have around 2,000 lines of server-side and client-side code.

 

TextBoxWatermark

The TextBoxWatermark extender is a great way to conserve screen real estate by superimposing descriptive labeling onto the surface of a blank TextBox Web control (see Figure 2). The watermark disappears as soon as the user enters text into the text box, so it doesn t obscure their input.

 


Figure 2: The TextBoxWatermark extender condenses labeling text by superimposing it onto a text box.

 

The TextBoxWatermark extender s public members consist of three public properties. The TargetControlID property is standard to all extenders. It must contain the ID of the TextBox on which the watermark should appear. The WatermarkText property sets or gets the exact text that should appear over the text box as the watermark. The WatermarkCssClass is used to adjust the appearance of the watermark. The following is a sample ASPX declaration:

 

<ajaxToolkit:TextBoxWatermarkExtender

   ID="TextBoxWatermarkExtender1"

   runat="server" TargetControlID="TextBox1"

   WatermarkCssClass="password_watermark"

   WatermarkText="Enter Password"

/>

 

FilteredTextBox

Another useful extender provided by the AJAX Control Toolkit is the FilteredTextBox. It helps ensure users don t input invalid values into text boxes. For example, it can prevent users from entering text where numbers are expected, and vice versa. A client-side timer is used to check the contents of the text box at regular intervals and remove any characters that shouldn t be there.

 

An examination of the FilteredTextBox extender s 96 lines of server-side source code reveals that no server-side validation is done by the control. Only client-side validation is performed automatically. Therefore, I suggest you use some custom server-side code along with this control as an additional validation check.

 

It is good practice to never rely exclusively on client-side validation checks. While it is true that client-side checks can t be beat from a usability perspective, server-side validation is a necessity from a security perspective. This is because JavaScript must be used for client-side validation and JavaScript is far too easy to evade or simply turn off. Therefore, top-notch Web developers tend to use both client-side and server-side validation to get the best of both worlds.

 

The FilterMode property can be set to either ValidChars or InvalidChars. This allows the developer to specify either a list of acceptable characters or unacceptable characters, respectively. To go along with this, there is a ValidChars property and an InvalidChars property used to specify exactly which characters are permitted or denied. However, all three of these properties are completely ignored unless the FilterType property is set to Custom. The FilterType property accepts any combination of the following four values, which must be comma separated: Numbers, Lowercase, Uppercase, Custom.

 

For example, the following sample ASPX declaration helps ensure users enter only numeric digits, along with a few other related symbols: a dollar sign, a comma, and a decimal point:

 

<ajaxToolkit:FilteredTextBoxExtender

    ID="FilteredTextBoxExtender1" runat="server"

   TargetControlID="TextBox1"

   FilterType="Custom,Numbers"

   ValidChars="$,."

/>

 

While this example helps ensure that only currency-related characters are entered into a text box, the FilteredTextBox extender cannot ensure they are entered in a valid order. For example, an entry such as 43,1.12$9 would unfortunately pass validation. This tends to limit the usefulness of the FilteredTextBox extender to fairly simple scenarios only. For more complex validation, you might instead prefer to use the MaskedEdit extender.

 

MaskedEdit

Like the FilteredTextBox extender, the MaskedEdit extender helps ensure users don t enter invalid values into textboxes. However, the MaskedEdit extender takes the idea to the next level by providing rich pattern-matching functionality to help ensure all characters are correctly positioned according to the type of input expected.

 

If you ve developed Windows applications using Microsoft s old masked edit ActiveX control, you ll feel right at home with this Webbed version. Like the aforementioned ActiveX control, the MaskedEdit extender has a Mask property to define the exact input format expected. It is similar in concept to regular expressions. For currency input you might choose to set the Mask property to 9,999,999.99 . You might also want a dollar sign to appear before the value by changing the DisplayMoney property from its default of None to Left. Similarly, you might also choose to permit negative values by changing the AcceptNegative property from its default value of None to Left. At run time, a text box extended with this mask would look like the image in Figure 3. If you dislike the underscore placeholder character, you can change it via the PromptCharacter property. By setting the ClearMaskOnLoseFocus property to True, such mask characters can automatically disappear when the textbox loses focus.

 


Figure 3: The MaskedEdit extender ensures user input matches a specified character pattern.

 

While the MaskedEdit extender is flexible enough to enforce virtually any input pattern, it provides enhanced support for date and time formats because they are so common. By default, the extender uses date and time input formats that are consistent with the culture setting of the page, although this behavior can be overridden in a variety of ways when desired. For example, the UserTimeFormat property can be used to toggle between a 12- or 24-hour clock. Similarly, the UserDateFormat property can be used to specify that date input should be in the order of day/month/year or month/day/year or any other combination.

 

There are a variety of ways the MaskedEdit extender can be configured to handle situations where a user may have neglected to enter one or more expected characters. For example, if the user forgets to enter the date s year, the current year may be filled in automatically as the default. Polished features such as this can dramatically expedite data entry for high-volume applications. Similarly, two-digit dates can automatically be filled in with the four-digit equivalent by setting the AutoComplete property to True and setting the Century property to 1900 or 2000. For numeric entry, blank digits can be automatically replaced with zeros.

 

The MaskedEdit extender s 32 properties also include a variety of styles for adjusting the run-time look and feel.

 

MaskedEditValidator

While the MaskedEdit extender is ideal for doing things like ensuring users enter dates where dates are expected and numbers where numbers are expected, it cannot by itself ensure that those values are within an acceptable range. This is where the MaskedEditValidator comes in.

 

If you ve ever worked with the standard ASP.NET validation controls, you ll have no further learning curve, as it is configured nearly identically. The MaskedEditValidator coordinates its efforts with a specified MaskedEdit extender and the TextBox that it in turn extends. The MaskedEditValidator s ControlToValidate property should be set to the ID of the TextBox, and the ControlExtender property should be filled with the ID of the TextBox s MaskedEdit extender.

 

The MaximumValue and MinimumValue properties are used to specify the acceptable range of input values. When these values are exceeded, the MaximumValueMessage and MinimumValueMessage properties are used for specifying the error message that should be displayed to the user. In situations where you d like an alternate message to be displayed when the TextBox loses focus, the MaximumValueBlurredMessage and MinimumValueBlurredMessage properties can be used. Similarly, there are InvalidValueMessage and InvalidValueBlurredMessage properties for other kinds of validation failures. Finally, there are EmptyValueMessage and EmptyValueBlurredMessage properties for unacceptable missing input.

 

The IsValidEmpty Boolean property can be used to indicate whether null input values are acceptable or not. The InitialValue property can optionally be filled to allow the validator to make intelligent decisions about whether the input has changed from its original value or not.

 

Just in case the rich Mask format of the MaskedEdit control isn t quite flexible enough for your needs (which should be rare, indeed), you can also employ the assistance of the MaskedEditValidator s ValidationExpression property. This property accepts any valid regular expression and uses it to validate the user s input.

 

Conclusion

The TextBoxWatermark extender is a great way to reduce screen clutter without skimping on potentially helpful descriptions. The FilteredTextBox is a simple extender with a relatively small learning curve that can be useful for basic input validation needs. More complex validation requirements may need to be handled by the meatier MaskedEdit extender. The learning curve for the MaskedEdit extender shouldn t be too scary if you ve worked with older masked input controls from Microsoft. Likewise, if you ve worked with the validation Web controls that came with ASP.NET 2.0, you should find the MaskedEditValidator to be fairly intuitive, as well. Its tight integration with the MaskedEdit extender is a nice fit that both users and developers should be able to appreciate.

 

You can start experimenting with all the controls in the AJAX Control Toolkit right now, without downloading a thing. To see them in action and begin tinkering, visit http://www.asp.net/AJAX/AjaxControlToolkit/Samples/.

 

For more in-depth tinkering, you ll want to download the toolkit (and perhaps its free source code) to your development machine: http://www.asp.net/AJAX/downloads/.

 

Additionally, there are several high-quality free learning videos available at http://www.asp.net/AJAX/AjaxControlToolkit/.

 

Like most open source projects, no company has expressed a willingness to provide professional support for developers using the toolkit. Therefore, a public forum is vital so we developers can help each other through any tough spots we may encounter during development. That forum is located at http://forums.asp.net/default.aspx?GroupID=34.

 

I wish you happy coding, and try not to get too distracted from your business goals by all the juicy goodness that the AJAX Control Toolkit has to offer!

 

Steve C. Orr is an ASP Insider, MCSD, Certified ScrumMaster, Microsoft MVP in ASP.NET, and author of Beginning ASP.NET 2.0 AJAX by Wrox. He s been developing software solutions for leading companies in the Seattle area for more than a decade. When he s not busy designing software systems, or writing about them, he can often be found loitering at local user groups and habitually lurking in the ASP.NET newsgroup. Find out more about him at http://SteveOrr.net or e-mail him at mailto:Steve@Orr.net.