3

I am using following js function in my asp.net MVC application on click of Ok button to make sure that value entered in the text box is integer but it always returns false;

function isInteger(n) {
    return n === +n && n === (n | 0);
}

and here is how I am using it:

  if (!isInteger(selectedPhoneValue)) {                      
     $("#dialog-numeric-phonevalidation").dialog('open');
      return;
     }

Please suggest me how to change this function to allow only positive integer/numberic value without "." and "-"

DotnetSparrow
  • 27,428
  • 62
  • 183
  • 316
  • How is `selectedPhoneValue` collected? – raina77ow May 07 '13 at 12:41
  • I've asked because I suspect it's taken directly from an input (with `input.value` or `$input.val()`, whatever). But these methods return you `String`; you should actually convert it to Number explicitly (I'd recommend `parseInt` here) before checking whether it's integer or not. – raina77ow May 07 '13 at 12:47
  • @raina77ow parseInt would chop off decimals and cause it to be true... – epascarello May 07 '13 at 12:50
  • Damn, of course. ) `parseFloat` should be used, if one wants to _check_ the input. `parseInt` is useful to bite the bullet in this case. ) – raina77ow May 07 '13 at 12:51
  • Is `3.0` valid? Or is it just 3? – epascarello May 07 '13 at 12:54
  • just 3, i want to use it for phone number – DotnetSparrow May 07 '13 at 12:57
  • Why force a user to enter in a specific format? I'd just strip any non-numeric characters and then check that it has a valid number of numeric characters and format it however I want. – Smern May 07 '13 at 12:59
  • Um wouldn't a phone number have to be certain number of digits? Seems weird you would be checking just int. – epascarello May 07 '13 at 13:12

2 Answers2

3

You can use regular Expresion instead

 function isInteger(n) {
        return /^[0-9]+$/.test(n);
    }
3
function isInteger(n) {    
    return $.isNumeric(n) && parseInt(n, 10) > 0;
}

Update:

Then change the if check like so:

//Assuming selectedPhoneValue is not already converted to a number.
//Assuming you want an exact length of 10 for your phone number.

if (isInteger(selectedPhoneValue) && selectedPhoneValue.length == 10) {
    $("#dialog-numeric-phonevalidation").dialog('open');
    return;
}

You can use this code to strip out the "." and "-" characters.

selectedPhoneValue = selectedPhoneValue.replace(/-/g, "").replace(/\./g, "");
rdp
  • 2,675
  • 2
  • 21
  • 21