Saturday, March 24, 2012

Text Masking

What is the easiest way to apply a Mask to data in ASP.NET. I have Phone Numbers stored in 5555555555 format in the database, and when I load them I'd like to mask them, where applicable, as (555) 555-5555. Is there an easy way to do this or am I gonna have to write something custom to do it?Take a look at the String.Format method it has everything you want and more!

String formatting in C# (http://www.stevex.org/CS/blogs/dottext/articles/158.aspx) -> C# article but still applies to VB.NET. It even has an example for phone numbers!

HTH

DJ
Thanks, that helps on the output. Still looking for thoughts on Input Masking as well. I've converting an old Access App to a SQL/ASP.NET app, and alot of the fields were masked to a certain input. I can do regular expression validators, but what a hassle to right them for every input and even then it doesn't seem as intuitive.
Could you give some more details of what you are doing - I don't understand why the above wouldn't work for the situation you describe. Perhaps I've misunderstood.

DJ
No, that will work great for when I output from the database. I'm just trying to figure out a way to mask data on input. For example, in this Access app I am converting to ASP.NET, for a phone number, it has an text field that looks something like: (___) ___-____ , where it restricts (masks) input.
Your best bet is to use javascript. I don't know if you are good with JS or not, but I am sure you could find sample code for formatting a phone number using it.

I recommend this because it will be 100% client side formatting, and won't be a drag on your webserver. If you were to make the input box run at the server, and put code in its textchanged event, each time they type a number in the box it would post back to your webserver. Javascript will simply do everything client side. it would be the onchange event of the input tag that you would want to perform the formatting. Basically you look at the entered string, get all the numbers in it, and if the numbers length is 10, then you have potentially a valid phone number and should format it, otherwise do not.

0 comments:

Post a Comment