0

In my application, there is a method which return values from the server. Format of the value which I am getting is in string.

MESSAGE : 
 url:'xxxxxx',
 date:'xx/xx/xxxx',
 time:'xx:xx:xx',
 body:"10"

Now in the body, there is an integer value but it is coming in string. There are possibility that instead of number in the string, irrelevant data can also come like float, characters, special symbols inside the string.

body:'157a'
body:'22/2'
body:'/45'

Now my requirement is, as I get the value I have to check whether the data coming in the form of string is the perfect integer or not. That should not be zero, negative, floating values or characters.

For example

format below is acceptable as per my requirement

body:'225'
body:'147'
body:'534'

format below is not acceptable as per my requirement

body:'0'
body:'-145'
body:'22/a'
body:'67,54'

I tried using parseInt() or isNan() but I have checked that if we do

var data = parseInt('76,54');
console.log(data);

that returns 76. But as per my requirement it should not come like that. Is there any way that I can check for the integer into the string which I am getting from the server.

Yash Jain
  • 752
  • 1
  • 12
  • 34
  • 1
    Possible duplicate of [Validate that a string is a positive integer](https://stackoverflow.com/questions/10834796/validate-that-a-string-is-a-positive-integer) – Vikasdeep Singh Jun 28 '18 at 06:51

4 Answers4

0

You can use a regular expression to verify that the value is a string of decimal digits.

function isIntegerDigits(s) {
  return /^[0-9]+$/.test(s);
}

["225", "147", "534", "0", "-145", "22/a", "67,54"].forEach(c =>
  console.log(c, isIntegerDigits(c) && parseInt(c) !== 0)
);

outputs

225 true
147 true
534 true
0 false
-145 false
22/a false
67,54 false
AKX
  • 152,115
  • 15
  • 115
  • 172
0

Yes its as easy

body*1 === parseInt(body*1,10) && body > 0

Check for this,You will get true only in case of positive integer

Shyam Tayal
  • 486
  • 2
  • 13
0

function checkNumber(x){
  console.log(!!Number(x))
}

let a = '123dx'
let b = '133'
let c = 'yx123'



checkNumber(a)//false
checkNumber(b)//true
checkNumber(c)//false

The safe way to check is to wrap it explicitly using Number and using a double negation !! to get the boolean value

Isaac
  • 12,042
  • 16
  • 52
  • 116
0

you do

if (+body && !(+body%1) && +body > 0) {
    // only positive numbers
}

this will +body cast the body value to number and check if it != 0 then +body > 0 check if is has positive value

Jairo Malanay
  • 1,327
  • 9
  • 13