1

I am working on an existing function to validate the Object value is numeric and accept only COMMA Character.

Obj = 1,2,3,4,

However function is not giving any results ..

var checkOK;
                if (isInt == true) {
                    checkOK = "0123456789";
                }
                else {
                    checkOK = "0123456789.";
                }


                for (i = 0; i < checkStr.value.length; i++) {
                    ch = checkStr.value.charAt(i);

                    for (j = 0; j < checkOK.length; j++) {


                        if (ch == checkOK.charAt(j)) {
                            if (isInt == true && j == 0) {
                                allValid = false;
                                break;
                            }
                            else {
                                break;
                            }
                        }
                        if (j == checkOK.length - 1) {
                            allValid = false;
                            break;
                        }
                    }

                    allNum += ch;
                }

if (allValid==false)
                {
                    alertsay = "Please enter only valid values "
                    alert(alertsay);
                    document.getElementById(obj.id).innerText="";
                    obj.focus();
                    return (false);
                }
goofyui
  • 3,362
  • 20
  • 72
  • 128

1 Answers1

1

In javascript you can do:

/^[0-9,]+$/g.test(checkStr);

This returns true if a STRING (not object) only contains numbers or numbers + comma at random places. (also returns true for string '123,,6'). Otherwise returns false.

If you want to check is the STRING is a number, with only 1 decimal point or comma, you can do:

!isNaN(checkStr);

This returns true if checkStr is or can be converted to a valid number. (from this post: Is there a (built-in) way in JavaScript to check if a string is a valid number?)

Community
  • 1
  • 1
wintvelt
  • 13,855
  • 3
  • 38
  • 43