简体   繁体   中英

How do I validate a price (number) textbox?

I have a Windows forms application written in C#.

I am looking for a way to validate my price textBox so that it only accepts prices in a double format eg allowing 0.01 & 1200.00 but provides an error when the user enters characters.

I would except the code to looks similar to

String price = tbx_price.Text.Trim();

if price is not a number
{
   error message
}
else{
...

What method could I use to check if the price string contains only numbers? Please note that I require the user to be able to use decimal places so the '.' character should be allowed.

Use decimal.TryParse :

decimal d;
if (!decimal.TryParse(price, out d)){
    //Error
}

And if you also want to validate the price ( 145.255 is invalid):

if (!(decimal.TryParse(price, out d) 
           && d >= 0 
           && d * 100 == Math.Floor(d*100)){
    //Error
}

You can test this using decimal.TryParse() .

For example:

decimal priceDecimal;
bool validPrice = decimal.TryParse(price, out priceDecimal);

If you can't be sure that the thread culture is the same as the user's culture, instead use the TryParse() overload which accepts the culture format (also the number format which you can set to currency):

public bool ValidateCurrency(string price, string cultureCode)
{
    decimal test;
    return decimal.TryParse
       (price, NumberStyles.Currency, new CultureInfo(cultureCode), out test);
}

if (!ValidateCurrency(price, "en-GB"))
{
    //error
}

Besides using the answer marked as accepted in order to avoid the problem with culture about prices, you can always use this

Convert.ToDouble(txtPrice.Text.Replace(".", ","));
Convert.ToDouble(txtPrice.Text.Replace(",", "."));

this will depend how you manage your convertion in your app.

PS: I could not comment the answer because i do not have the neccesary reputation yet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM