0

Would like to check the validation for an integer value using JavaScript. At the moment, this works fine for integers, but I want it to allow an empty string, ""

 function validateInt(inputString, columnName) {
    var errorOutput = "";

    var isNum = /^\d+$/.test(inputString);

    if (!isNum) {
        errorOutput += "<br>* Column " + columnName + " can only contain numbers. ";
    }

    return errorOutput;
}

An extra condition in the var isNum = ...? Any ideas?

apsillers
  • 112,806
  • 17
  • 235
  • 239
John
  • 3,965
  • 21
  • 77
  • 163

4 Answers4

2

Use the * modifier (zero or more) instead of the + modifier (one or more):

var isNum = /^\d*$/.test(inputString);

This will allow digit-only strings that have zero digits (i.e., the empty string) or some positive number of digits.

apsillers
  • 112,806
  • 17
  • 235
  • 239
0

Maybe going simply by using

if (!isNum || inputString === "") {
    ...
leopik
  • 2,323
  • 2
  • 17
  • 29
  • Should that be `!==` as the OP wants to allow `""`. Also, the first check `!isNum` would be true when the value is empty. So you need to check for empty value before using regex check. eg, `if (inputString !== "" && !isNum) {` – Kami Sep 30 '14 at 13:14
0

Use modulus by 1, to allow empty string when validating integers:

var isNum = inputString % 1 === 0;

As said in the comments, this will allow hexadecimal, binary, and other number representations that can be parsed by parseInt. It may not suit your particular case, if you don't want to allow those formats, but those are technically integers as well, for anyone who finds this and needs that functionality. If you use parseInt() on the input before doing anything with it, I don't see any harm in using it (correct me if I'm wrong).

Alex W
  • 37,233
  • 13
  • 109
  • 109
  • This still allow `""` as input. – DontVoteMeDown Sep 30 '14 at 13:12
  • @DontVoteMeDown He said he wants to allow empty string – Alex W Sep 30 '14 at 13:13
  • Be warned that this will allow hexadecimal and scientific notation in input strings: `"0xFAD" % 1 === 0` and `"1e10" % 1 === 0` are both `true`. See ES5's [*ToNumber Applied to the String Type*](http://www.ecma-international.org/ecma-262/5.1/#sec-9.3.1) for how strings are coerced to integers. – apsillers Sep 30 '14 at 13:13
0

In that case you cannot relive if(value) or if(value == "") in a single condition. You must write two statement for this. try if(value || value == '') also.

Isha John
  • 593
  • 2
  • 5
  • 16