ericb ericb - 1 year ago 65
Javascript Question

Regex 0's after decimal

I have a regex method that i'm trying to use to check for a decimal and only allow 2 numbers after it. So for example this should return true if you had 1.00 and false if 1.000 which it does but I also want it to return false if 1.3 or 1
Not sure if I have something backwards or missing something here.

validateDecimal : function(value) {
var regex = new RegExp(/^\d*\.\d\d$/);
if (regex.test(value)) {
return true;
} else {
return false;

Answer Source

According to examples you provided, what you want is:


Let's take it step by step:

  1. \d* - match any digit and any amount of digits, so "1", "23", "3535" are matching
  2. \. - literal dot
  3. \d{2} - match only if there are two digits, so "00", "22", "56" are matching but "1" or "000" are not

You can test your javascript regular expressions with this convenient online tool. Also here is a great website that allows you to analyze your regex and learn more about it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download