Create Custom Input Boxes

Learn to create masked edit boxes by using regular expressions.

asp.netNOW Q&A

LANGUAGES: VB .NET | C#

TECHNOLOGIES: Regular Expressions

 

Create Custom Input Boxes

Learn to create masked edit boxes by using regular expressions.

 

By Josef Finsel

 

Q: I am fairly new to ASP.NET. One thing I haven't been able to figure out is how to create an Input Mask for textboxes. I would like to specify a format for the users to view and input their values, but I don't want those values saved when the form is submitted. Any suggestions?

 

A: This is one of those questions that seems like it should be easier than it is. Masked edit boxes have been around for some time in VB, allowing you to show a phone number such as 5135551212 in the form (513)555-1212, yet it still gives 5135551212 as the value.

 

One problem with the client-side scripts that have been around is that the formatted number is what is returned as the value. There are a couple of ways around that in .NET, though. The first - and clumsiest - is to use another field to hold the original data. The only field that really fits the bill for this would be the toolbar, so let's look at how you could do this.

 

Start by using the TextChange method of a textbox, setting the ToolTip property to the non-formatted value, then set the Text property to the formatted one. Fortunately, you can do this in two lines of code using regular expressions. In the September 2002 issue of asp.netPRO, Steven Smith wrote an excellent article on regular expressions entitled Create No-Sweat Regular Expressions, so I won't go into the basics. Instead, I'll focus on one aspect - the Replace method. First, note the code samples for this column are in VB .NET, but you can download the C# version.

 

The replace method does exactly what you might think: It replaces text with matching text, except it does so in a far more powerful manner than its simple cousin found in string functions. Take a look at what you're trying to do: You want to take a 10-digit number and format it. But you don't want to format it into a 10-digit number; instead, format it into three separate sets of numbers: an area code, a prefix, and a line. Fortunately, the RegEx class can handle this as long as you ask it nicely by breaking the 10-digit number into sections. So instead of using \d{10} to signify a 10-digit number, you use (\d{3})(\d{3})(\d{4}). By separating the numbers using parentheses, you're telling RegEx to treat these as three distinct subsets that can be referred to by a $, followed by the number of the group. Thus, 5135551212, when parsed through (\d{3})(\d{3})(\d{4}), becomes $1=513, $2=555, $3=1212. Now you can use the Replace method of the RegEx class to transform your text like this:

 

Regex.Replace(txtPhone.Text, "(\d{3})(\d{3})(\d{4})", "($1) $2-$3")

'5135551212 -> (513) 555-1212

 

You want to keep the value clean yet still display the formatted version, so store the original value in the ToolTip property and your TextChange method looks like this:

 

txtPhone.ToolTip = txtPhone.Text

txtPhone.Text = Regex.Replace(txtPhone.Text, "(\d{3})(\d{3})(\d{4})", "($1) $2-$3")

 

Now, when you want to get the value of the phone number, simply get the ToolTip. But that's clunky. Instead, use RegEx to reverse the formatting. Unfortunately, this is a little more complicated than it might appear because you have increased the number of elements you're dealing with dramatically - from three to seven. Don't believe me? See for yourself:

 

1

2

3

4

5

6

7

(

513

)

555

-

1212

 

The good news is RegEx handles this easily, and it's simple as long as you take it one step at a time. To remove the format from the phone number, simply execute this code:

 

Regex.Replace(txtPhone.Text, "(\(\d{3})(\))( )(\d{3})(-)(\d{4})", "$2$5$7")

 

There is, however, a problem with everything I've talked about so far. Although RegEx can replace data that matches, it doesn't work for data that doesn't match exactly. In other words, if you enter 51355512 and exit the textbox, the TextChange method would fire, but it wouldn't format the string to (513) 555-12 because the last set of numbers has only two digits, not four.

 

Seemingly the answer would be to use a regular expression Validator. But that won't work because you need to use the AutoPostBack on the TextBox, and you're modifying the Text value the Validator needs to use to validate data. All is not lost, it's just a little more complex - simply fire the Validator manually. This means you must check to see if the text is correct, then fire the Validate event only if it isn't. Here's the finished code:

 

Private Sub txtPhone_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) _

           Handles txtPhone.TextChanged

   If Regex.IsMatch(txtPhone.Text, "\d{10}") Then

       txtPhone.Text = Regex.Replace(txtPhone.Text, "(\d{3})(\d{3})(\d{4})", "($1) $2-$3")

   ElseIf Not Regex.IsMatch(txtPhone.Text, "(\()(\d{3})(\))( )(\d{3})(-)(\d{4})") Then

       rePhoneNumber.Validate()

   End If

End Sub

 

First, check to see if the text contains 10 digits. If it does, reformat it; if not, check to see if it contains formatted code. If it doesn't contain formatted code, fire the regular expression Validator, which contains both possibilities you checked for.

 

This is all wrapped in a nice little package in the downloadable code. Also, you can use this with other expressions. You can find a good resource for regular expressions that have been tested already at http://www.regexlib.com.

 

Keep your ASP.NET questions coming! E-mail me at [email protected].

 

The code referenced in this article is available for download.

 

Josef Finsel is a software consultant with a global consulting firm and specializes 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 aspnetpro 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 (Apress).

 

 

 

 

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