Data Conversion and Validation
page 6 of 7
by Brian Mains
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 35710/ 62

Data Input

Within ASP.NET, data is most often input through textbox controls, although this varies based upon the need. A Textbox is used to input names, numbers, dates, and inputs of other types.  With the AJAX control toolkit, it is easy to restrict the type of input into the textbox.

When trying to extract the values from the textboxes and converting them to their correct data type, there are some challenges you have to be aware of.  For instance, with a DateTime data type, the input has to be checked to ensure it is correct. If the user enters the following values:  13/13/2008, 1/113/2008, 4/32/2008, when these values are passed to DateTime.Parse or Convert.ToDateTime, an exception will be thrown.

It is better to use DateTime.TryParse instead to get to the date's value. TryParse returns back an empty value, and returns false if the value is invalid. The same concept applies to numerical values; TryParse, at least, fails gracefully. Failing gracefully is a good safeguard to prevent an error.

Ideally, it is best to restrict or prevent the invalid input in the first place. The AJAX control toolkit contains control extenders that restrict the input into it. For instance, the masked edit extender can restrict the input to fit money, date, and numerical input.

Listing 7

<ajax:MaskedEditExtender id="ext" runat="server" Mask="99/99/9999" MaskType="Date" />

As an alternative, the filtered textbox extender restricts the type of characters that can be entered into it.  It can control input to be only numbers, only lowercase letters, uppercase letters, custom letters, or any combination. Below filters out numbers, but allows a decimal point.

Listing 8

<ajax:FilteredTextBoxExtender id="ext" runat="server" 
  FilterType="Numbers,Custom" ValidChars="." />

Make sure you use of the validation controls as well. Validation controls restrict invalid input being entered. For instance, even though the FilteredTextBoxExtender filters out values other than numbers or decimals, it will allow more than one decimal point. The regular expression validator below will prevent that.

Listing 9

<asp:RegularExpressionValidator id="rev" runat="server" ControlToValidate="txt"
ErrorMessage="Enter a valid dollar amount" ValidationExpression="\d+\.\d{2}" />

So plan your interface accordingly.


View Entire Article

User Comments

Title: good   
Name: jay
Date: 2010-01-29 1:45:56 AM
Comment:
good article.. but confusing words....






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2021 ASPAlliance.com  |  Page Processed at 2021-11-29 6:44:49 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search