1

Possible Duplicate:
Regular expression to match numbers with or without commas and decimals in text

var regex =  /^[0-9][0-9]{0,5}$|^[0-9][0-9]{0,5}[\.][0-9]$/;

valid values are 3,000 30,000 looking to have comma in the above regex . I could not get it

Community
  • 1
  • 1
Someone
  • 10,405
  • 23
  • 67
  • 100

1 Answers1

2

This regex will test for commas being in the right place:

/^[0-9]{1,3}(,[0-9]{3})*(\.[0-9]*)?$/

You can see a working example that validates as you type here: http://jsfiddle.net/jfriend00/u9VRX/

By way of explanation, the regex is:

start of string
1-3 digits
followed by 0 or more sequences of ,nnn where n is a digit
followed by an optional sequence that starts with a period
   and consists of 0 or more digits
end of string

If you don't require commas and are going to parse the number anyway, then it's easiest to just remove any commas first thus ignoring them:

var numStr = str.replace(/,/g, "");

If you want to know exactly what is wrong when it's invalid, then that's much more difficult to do with a pure regex. I would not find that the simplest way to solve the problem and it doesn't generally tell you what is wrong with the number either so I would use some plain javascript first.

function checkValid(str) {
    // check for legal characters
    if (!str.match(/^[0-9,]+(\.[0-9]*)?$/)) {
        // illegal characters present
        return("illegal_chars");
    }

    // strip off trailing decimal part
    var parts = str.split(".");
    if (parts.length > 2) {
        // too many periods
        return("too_many_periods");
    }

    // split each comma segment (if there are any)
    parts = parts[0].split(",");
    if (parts.length > 1) {
        for (var i = parts.length - 1; i > 0; i--) {
            if (parts[i].length != 3) {
                // wrong number of digits between commas 
                return("wrong_digits_between_commas");
            }
        }

        if (parts[0].length > 3) {
            // wrong number of digits in first segment before first comma
            return("too many digits before first comma");
        }
    }

    // if you got here without any errors, then all commas are legal
    return("");  // indicate success
}

You can see this one working as you type here: http://jsfiddle.net/jfriend00/W6FnT/

jfriend00
  • 683,504
  • 96
  • 985
  • 979