简体   繁体   中英

Validate currency format in C#

I would like to validate whether a string satisfy the following currency format with maximum 4 decimal places and could allow comma , regardless of culture and the comma could be at places of standard practice .

Eg:

2,000,000(valid)  
200000.0000(valid)  
200 (valid)  
200.00000(invalid)

How could it be done?

You can do Regex match for your purpose.

The Regex below works for your specific examples. But, it'll accept comma , at random places. Demo here.

^\d+(\,\d+)*(\.\d{1,4})?$

A better Regex would be the following. Check the demo . Base Regex taken from this post.

^\$?(\d{1,3},(\d{3},)*\d{3}|\d+)(.\d{1,4})?$

Update

To answer comment - above Regex allows 0090 . Try this one. Demo here .

^((([1-9]\d{0,2},(\d{3},)*\d{3}|[1-9]\d*)(.\d{1,4})?)|(0\.\d{1,4}))$

Update 2

C# usage

var currencyString = "1,234,456.7890";
var regex = @"^((([1-9]\d{0,2},(\d{3},)*\d{3}|[1-9]\d*)(.\d{1,4})?)|(0\.\d{1,4}))$";
var isValidCurency = Regex.IsMatch(currencyString, regex);

Update 3

As per OP, comma , is allowed at any place. Updated Regex with demo here .

^(([1-9]\d*(\,\d+)*(\.\d{1,4})?)|(0\.\d{1,4})|0)$

Update 4

Use this one. Demo HERE .

^((([1-9]\d{0,2}(,\d{3})*)(\.\d{1,4})?)|[1-9]\d*|(0\.\d{1,4})|0)$

Well, this :)

^((([1-9]\d{0,2}(,\d{3})*|[1-9]\d*)(\.\d{1,4})?)|[1-9]\d*|(0\.\d{1,4})|0)$

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