How to validate a percentage to two decimal places with a Regex?
18,130
Solution 1
In Perl:
/(^100([.]0{1,2})?)$|(^\d{1,2}([.]\d{1,2})?)$/
or you can just add an extra if comparing 100 exactly :)
Solution 2
This allows all percentages except zero.
^[1-9]{1}[0-9]?(?:\.\d{1,2})?$|^0\.\d{1,2}?$|100
Author by
littlechris
Developer mainly using .Net, SQL Server, Eclipse, Delphi.
Updated on June 20, 2022Comments
-
littlechris almost 2 years
Is there a regex that would validate a percentage value to 2 decimal places?
I have a regex for two decimal places, but don't know how to stop values above 100. e.g. 100.01 is validated with my regex.
-
Russell Smith over 14 yearsThat solution misses the value '100' or '100.00'.
-
Steve Wortham over 14 yearsNicely done. It works with my test cases... regexhero.net/tester/?id=6807190b-cc82-4dd4-8864-05ce8c0c3b4f
-
littlechris over 14 yearsLooks like it works on the link provided, but can get it to work in my app. ASP.Net MVC vlaidation using data annotation: [RegularExpression(@"/(^100([.]0{1,2})?)$|(^\d{1,2}([.]\d{1,2})?)$/")]
-
MSalters over 14 yearsYo can refactor this for better efficiency. The two parts before and after the | share an initial prefix and postfix, and it includes ^ and $. By making common parts common, you reduce the amount of backtracking needed when a part fails to match.
-
DVK over 14 years@littlechris - I'm not really familiar with ASP, sorry. Your initial question's tag was not .net specific. As stated, this was Perl - I'm unsure of the portability to .net
-
littlechris over 14 yearsthnkas DVK. my mistake I thought regex where pretty standard. Cheers! +1
-
Steve Wortham over 14 years@littlechris - Try removing the forward slash at the beginning and end. It should work just fine in .NET (that's what Regex Hero is using).
-
DVK over 14 yearsDuh... slashes are Perl RegEx operator. The pattern is inside the slashes. Sorry for confusion.
-
Fjut over 6 yearsYou should add ^100$ instead of the 100 at the end of your expression, otherwise anything containing 100 is considered valid e.g. 100s.23