Textbox for displaying and validating curreny in ASP.Net C#

Creating a textbox in asp.net that validates and formats a user input for currency
Originally Published: 9/17/2010

Chances are you will need a textbox to handle the formatting of currency. This example uses an asp.net textbox and ajax to validate and format the inputs. It's something that ASP.net should really provide out of the box. Most of the time I find myself using textboxes for things that really aren't text (i.e. Dates/Currency/ID Strings).

This example relies on a regular expression to validate the currency. It really is a nice way of validating controls because of the amount of control you can have on the user's input. The regular expression I found matches the following : ($4,000.00), -$4000.00, -$400.00

  1. Creating an ASP.net C# currency control GUI side.

    Here's the control in action:

     

    Theres not much at all to this control; its just two controls wrapped in an UpdatePanel to handle Microsoft's Ajax. The textbox is used to get the users input, and the regular expression validator will automatically fired when the text box is changed. There isn't antything else to do to get the validation to work. It really is a nice control to use instead of writing Javascript.

    Download the Control
  2. Heres the code behind for the page.
                    
                       

  3. Final Note

    Just Change the regular expression and the function to format the currency to whatever you want (dates, guids). The concepts are the same. Just use a regex to validate the input, then call a function to display the formatted value back to the user. This can also be done in Javascript. I chose to do this on the server side because I know that it will format the value of the textbox in way that will make the C# compiler happy.