-4

Given:

 var input_val = $('#field').val();

How do I check whether input_val contains only numbers or commas? The solution must work in the 4 main browers.

Hard worker
  • 3,378
  • 3
  • 37
  • 66
  • 1
    There was a similar post to this a couple of years ago. http://stackoverflow.com/questions/4246077/simple-problem-with-regular-expression-only-digits-and-commas – Gaz Winter Jun 13 '12 at 10:22
  • 1
    Do you mean "digits" (e.g. `0`, `1` etc) or "numbers" (e.g. `-3.14`)? – georg Jun 13 '12 at 10:24
  • Perhaps large US numbers like `1,000,000` or numbers with European decimal point: `3,14` - we will not know unless @Hard worker works harder on how he asks questions ;) And actually it sounds like homework even, so how hard does hard worker works? – mplungjan Jun 13 '12 at 10:54

3 Answers3

1

/^(\d|,)+$/.test(input_val) will return true as long as input_val only contains digits and/or commas.

mVChr
  • 46,510
  • 10
  • 101
  • 99
0

Use the following function

function containsNumbersAndCommasOnly(str) {
     return /^[0-9,]+$/.test(str);
}

by calling

if (containsNumbersAndCommasOnly(input_val)) {

}
Dan Lister
  • 2,337
  • 1
  • 19
  • 34
0

This is a combination of the response from @Adil and a community post answer from a different post. The combination of the two works better than either individually but there are still some issues... 12,12,12 would be valid here so would 1,,,,,,,,,9 as pointed out as @mplungjan.

For my purposes this is as far as I am willing to go but someone good with regex might add a solution that detects for single instances of commas followed but not preceded by a minimum of 3 digits.

if(!(!isNaN(parseFloat(n)) && isFinite(n))){
    return /^(\d|,)+$/.test(n);
}else{
    return true;
}
Community
  • 1
  • 1
carruthd
  • 311
  • 3
  • 8