Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force ASP.NET textbox to display currency with $ sign

Is there a way to get an ASP.NET textbox to accept only currency values, and when the control is validated, insert a $ sign beforehand?

Examples:

10.23 becomes $10.23
$1.45 stays $1.45
10.a raises error due to not being a valid number

I have a RegularExpressionValidator that is verifying the number is valid, but I don't know how to force the $ sign into the text. I suspect JavaScript might work, but was wondering if there was another way to do this.

like image 816
Jason Z Avatar asked Nov 29 '22 07:11

Jason Z


2 Answers

The ASP.NET MaskedEdit control from the AJAX Control Toolkit can accomplish what you're asking for.

like image 94
Forgotten Semicolon Avatar answered Dec 06 '22 04:12

Forgotten Semicolon


I know an answer has already been accepted, but I wanted to throw out another solution for anyone with the same problem and looking for multiple workarounds.

The way I do this is to use jQuery format currency plugin to bind user input on the client side. Parsing this input on the server side only requires:

// directive
using System.Globalization;

// code
decimal input = -1;
if (decimal.TryParse(txtUserInput.Text, NumberStyles.Currency, 
    CultureInfo.InvariantCulture, out input))
{
    parameter = input.ToString();
}

The only downfall to this is that the user can have javascript turned off, in which case the RegEx validator running server-side would work as a fall-back. If the control is databound, all you have to do is decimalValue.ToString("{0:c}") , as mentioned by others, in order to display the proper currency formatting.

The cool thing about this is that if the user enters the textbox and it shows $0.00 on the client side, the server-side if statement would return false. If your decimal value isn't nullable in the database, just change decimal input = -1 to decimal input = 0 and you'll have a default value of 0.

like image 22
Jim Schubert Avatar answered Dec 06 '22 03:12

Jim Schubert