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.
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.
/^(\d|,)+$/.test(input_val)
will return true
as long as input_val
only contains digits and/or commas.
Use the following function
function containsNumbersAndCommasOnly(str) {
return /^[0-9,]+$/.test(str);
}
by calling
if (containsNumbersAndCommasOnly(input_val)) {
}
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;
}