Regex for Money

I have asp:TextBox to keep a value of money, i.e. ‘1000’, ‘1000,0’ and ‘1000,00’ (comma is the delimiter because of Russian standard).

What ValidationExpression have I to use into appropriate asp:RegularExpressionValidator?

I tried d+,d{0,2} but it doesn’t allows a number without decimal digits, e.g. just ‘1000’.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

d+(,d{1,2})?

will allow the comma only when you have decimal digits, and allow no comma at all. The question mark means the same as {0,1}, so after the d+ you have either zero instances (i.e. nothing) or one instance of

,d{1,2}

As Helen points out correctly, it will suffice to use a non-capturing group, as in

d+(?:,d{1,2})?

The additional ?: means that the parentheses are only meant to group the ,d{1,2} part for use by the question mark, but that there is no need to remember what was matched within these parenthesis. Since this means less work for the regex enginge, you get a performance boost.

Method 2

We use this very liberal regular expression for money validation:

new Regex(@"^-?(?$?s*-?s*(?(((d{1,3}((,d{3})*|d*))?(.d{1,4})?)|((d{1,3}((,d{3})*|d*))(.d{0,4})?)))?$");

It allows all these:
$0, 0, (0.0000), .1, .01, .0001, $.1, $.01, $.0001, ($.1), ($.01), $(.0001), 0.1, 0.01, 0.0001, 1., 1111., 1,111., 1, 1.00, 1,000.00, $1, $1.00, $1,000.00, $ 1.0000, $ 1.0000, $ 1,000.0000, -1, -1.00, -1,000.00, -$1, -$1.00, -$1,000.00, -$ 1, -$ 1.00, -$ 1,000.00, $-1, $-1.00, $-1,000.00, $(1), $(1.00), $(1,000.00), $ (1), $ (1.00), $ (1,000.00), ($1), ($1.00), ($1,000.00)

Method 3

http://regexlib.com/Search.aspx?k=money

Method 4

i used this one in javascript: may be of use for you in c#

var entered = '10.00';
var regex = /^d+(?:.d{2})?$/; // starts with N digits optional ".dd"
console.log(entered.match(regex));


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x