tags:

views:

56

answers:

5

Hi Team,

I have a javascript requirement.

I will pass a comma separated string into a function. I need to ensure that it contains only integers (without decimals) and the value is less than 2147483648. Could you please help me ?

Note:: I am working on IE 6

Thanks

Lijo

A: 

parseInt() will handle the string -> integer conversion for you. As far as the figure goes, just test it using a conditional if/then:

var new_integer = parseInt(passedString);

if(new_integer < 2147483648){
    /* do something */
} else {
    /* do something else */
}
dclowd9901
A: 

You can do something like this:

function getNumberArrayFromString(str) {

   var numbers = str.split(",");
   var numbersArr = new Array();

   for(var i = 0; i < str.length, i++) {
       var number = parseInt(str[i]);

       if(!isNan(number) && number < 2147483648) {
          numbersArr[numbersArr.length] = number;
          //You can also use numbersArr.push(number) but I'm not sure if that's supported in IE6
       }
   }

   return numbersArr;
}

Assuming I understand your question correctly.

Vivin Paliath
A: 
function isValid(s){
  try { 
    return parseInt(s.replace(",","")) < 2147483648;
  } catch (e) {
    return false;
  }
}
z5h
A: 

Try this

function check(string){
    var s = string.split(',');
    for(i = 0; i <= s.length; i++){
        if(!isNaN(s[i]) && i >= 2147483648){
            return false
        }
    }
}
Ben Shelock
where is `return true`?
EFraim
Just check if it returns false then act acorrdingly.
Ben Shelock
would need to be "check(myString) === false" (because == will always be false)
plodder
+1  A: 
function validate(str){
    str=str.split(",")
    for(var a=0;a<str.length;a++){
        if(!str[a].match(/^[0-9]+$/)){
            return false
        }
        if(str[a]*1>=2147483648){
            return false
        }
    }
    return true
}

This doesn't accept negative integers or empty strings, should it?

eBusiness
this is only one so far that does everything he asks - just out of curiosity, why *1 in str[a]*1 - won't auto-coercion handle it?
plodder
After doing a test, it seems like it would be correct without the *1, but since >= is also a string operator I wasn't sure. Try to compare two stringified numbers, and you are in trouble.
eBusiness