Force ASP.NET text field to display currency using the $ sign

Is there a way to force the ASP.NET text box to accept only currency values, and when the control is checked, insert the $ sign in advance?

Examples:

10.23 becomes $ 10.23
$ 1.45 remains $ 1.45
10.a causes an error due to the lack of a real number

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

+3
source share
6 answers

, , , .

, , - jQuery . :

// directive
using System.Globalization;

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

, javascript, RegEx, , . , , , decimalValue.ToString("{0:c}"), , .

, , $0.00 , false. , decimal input = -1 decimal input = 0, 0.

+5

Another way to do this is to place the dollar sign to the left of the text box. Is there a real need to have a dollar sign inside the box or will a simple label make it?

+4
source
decimal sValue = decimal.Parse(txtboxValue.Text.Trim());
// Put Code to check whether the $ sign already exist or not.
//Try making a function returning boolean
//if Dollar sign not available do this
{ string LableText = string.Format("{0:c}", sValue); }
else
{ string LableText = Convert.ToString(sValue); }
+2
source
string sValue = Convert.ToString(txtboxValue.Text.Trim());
// Put Code to check whether the $ sign already exist or not.
//Try making a function returning boolean
//if Dollar sign not available do this
{ string LableText = string.Format("{0:c}", "sValue"); }
else
{ string LableText = Convert.ToString(sValue); }
+1
source

In .CS, you can match patterns by lines,

string value = text_box_to_validate.Text;

string myPattern = @"^\$(\d{1,3},?(\d{3},?)*\d{3}(\.\d{0,2})|\d{1,3}(\.\d{2})|\.\d{2})$";
Regex r = new Regex(myPattern);
Match m = r.Match(value);

if (m.Success)
{
    //do something -- everything passed
}
else
{
    //did not match
    //could check if number is good, but is just missing $ in front
}
0
source

Source: https://habr.com/ru/post/1698270/


All Articles