huMpty duMpty
huMpty duMpty

Reputation: 14460

Validate number with currency symbol

I have a grid with represent currency value including the symbol.

User can edit the field which will be updated on after_edit event.

I am trying to validate the user input to accept only valid ones. I cannot use normal regex to validate the number @"^\d{9}$" as it contains the symbol.

I looked at this question about Regular expression to remove any currency symbol from a string? but didn't help.

if the input is "$2ss50.00" it matches and return 2.

Is there anyway that I can do the update if only input like $250.00, £24.50 etc... as the grid value is set using value.ToString("c2",culture);

Upvotes: 1

Views: 1136

Answers (2)

zx81
zx81

Reputation: 41838

\p{Sc} matches a character from the Unicode category “currency symbol” (any currency sign) in .NET as well as Perl, PCRE, Ruby and Java.

Use this:

^\p{Sc}?[0-9]+\.[0-9]{2}$

If the decimals are optional, make it:

^\p{Sc}?[0-9]+(?:\.[0-9]{2})?$

Explanation

  • The ^ anchor asserts that we are at the beginning of the string
  • \p{Sc}? matches an optional currency symbol.
  • [0-9]+ matches one or more ASCII digits
  • \. matches the decimal point
  • [0-9]{2} matches the decimals
  • The $ anchor asserts that we are at the end of the string

Upvotes: 3

DavidG
DavidG

Reputation: 118987

If you know the culture, this can be done in C# like this:

float value;
var culture = CultureInfo.GetCultureInfo("en-GB");
bool isValidCurrency = float.TryParse(str, NumberStyles.Currency, culture, out value);

Upvotes: 5

Related Questions