JSFiddle - React, Tailwind, and code Playground

by jfriend00

HTML

Type a number here:<br>
<input type="text" id="test"><br>
<div id="result"></div>

JavaScript

function checkValid2(str) {
    var regex = /^[0-9]{1,3}(,[0-9]{3})*(\.[0-9]*)?$/;
    return (regex.test(str) ? "OK": "BAD");
}

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("OK");  // indicate success
}

$("#test").keyup(function() {
    var ret = checkValid(this.value);
    $("#result").html(ret);
});