0

I need to validate whether a input is a valid integer allowing for +/- entries.

I have tried this.

 function valid(elem)
 { 
      var num = parseInt(elem);
      if(!Number.isInteger(num))
      {
         alert ("Not an integer");
      }
 }

But the issue here is , it is validating even strings like 10sd as an integer. So how to validate this?

I want to validate as following:

valid(-10) = true;
valid(+10) = true;
valid(-10.01) = false;
valid(10sd) = false;
valid(10.23see) = false;
valid(10) = true;
9
  • 2
    Is hexadecimal, octal or binary input valid? Depending on what you consider valid, a regular expression might be the simplest approach. Commented Nov 21, 2019 at 10:56
  • @NickParsons: That alone is not enough. isNaN("5.5") is false. Commented Nov 21, 2019 at 10:57
  • @FelixKling oh, I see. My bad Commented Nov 21, 2019 at 10:58
  • @FelixKling just plain numbers Commented Nov 21, 2019 at 11:00
  • With "plain numbers" I assume you mean decimal numbers. Is the input a string or a number? Do you want it to accept strings? (I assumed since you use parseInt but I'm not sure anymore; it's also unclear whether +/- just means positive or negative numbers or whether a string can start with + or -). Commented Nov 21, 2019 at 11:02

2 Answers 2

0

Simple

function valid(elem){return parseInt(elem)==elem}
Sign up to request clarification or add additional context in comments.

3 Comments

If you already know that a value is a number (typeof elem=="number") why do you use parseInt? parseInt converts strings to numbers.
We need to determine if it is an integer. in fact, this is enough for this task, so the function can only be: function valid(elem){return parseInt(elem)==elem}
Then I would suggest Math.floor(elem) === elem instead. Of course the whole function can be replaced with Number.isInteger instead.
0
function valid(value) {
   if(typeof value === 'number' && isFinite(value))
       alert ("It is an integer");
}

This function does the job, typeof is a keyword in Javascript which tells you the data type of the variable

You can check this out, for more usage of typeof: https://webbjocke.com/javascript-check-data-types/

Edit: made a silly error in alert, it should alert if it is an integer, the if condition checks for number

2 Comments

valid(5) says "Not an integer".
Sorry for the error, answer updated

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.