How to check if an input box contains only numbers or commas?


 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);
    return true;

Need Your Help

Performing CRUD operations using Servlet/JSP

jsp servlets crud

I'm performing CRUD operations using Servlet and JSP. The following class is used to retrieve a connection from a connection pool maintained by a server (Tomcat).

UTF8 and JSON in Flask

python json unicode utf-8 flask

In Flask/Python We have a dictionary like this created by the json.loads function: