4

I want to validate a input field. The user should type in a phone number with minimum length of 10 digits.

So I need to check for illegal chars. It would be nice just to check wheather the input is an integer or not.

I came up with this but it does not work (n would be the string).

function isInt(n){
    return typeof n== 'number' && n%1==0;
}

Any ideas?

DarkLeafyGreen
  • 69,338
  • 131
  • 383
  • 601

5 Answers5

12

You can do a test like this:

input.length >= 10 && /^[0-9]+$/.test(input)

That will fail if there are non-digits in the string or the string is less than 10 chars long

Martin Jespersen
  • 25,743
  • 8
  • 56
  • 68
  • 1
    +1 for answering the actual question (although probably good to check whether it's already a number). But as Diodeus points out, phone numbers aren't integers, steering the OP another way would be good. – T.J. Crowder Jan 14 '11 at 14:16
  • 4
    Just using regex `^[0-9]{10,}$` would be enough – darioo Jan 14 '11 at 14:19
  • it's a regex method that returns a boolean indicating weather a regex passed or not. See more here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp/test – Martin Jespersen Jan 14 '11 at 14:22
3

This should work((input - 0) automatically tries to convert the value to a number):

function isInt(input){
   return ((input - 0) == input && input % 1==0);
}

There is already an SO-question about this issue: Validate decimal numbers in JavaScript - IsNumeric()

Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
1

Might be an overkill for you, but Google has not too long ago announced a library for phone validation. Java and Javascript variants are available.

darioo
  • 46,442
  • 10
  • 75
  • 103
1

Validating a phone number is a little more complicated than checking if the input is an integer. As an example phone numbers can and do begin with zeros so it isn't technically and int. Also users may enter dashes: For example:

00 34 922-123-456

So, as for validating it you have a couple of options:

  • Use regex expression to validate, have a look at:

    http://regexlib.com/

    this site will have hundreds of examples

  • Use looping to check each characters in turn, i.e. is character int or dash

I would recommend the former as the latter depends on consistent input from users and you aren't going to get that

MrEyes
  • 13,059
  • 10
  • 48
  • 68
0

Why not use:

return (+val === ~~val && null !== val);

as a return in your function?

this is the output of the javascript console

> +"foobar" === ~~"foobar"
  false
> +1.6 === ~~1.6
  false
> +'-1' === ~~'-1'
  true
> +'-1.56' === ~~'-1.56'
  false
> +1 === ~~1
  true
> +-1 === ~~-1
  true
> +null === ~~null // this is why we need the "&& null !== val" in our return call
  true 
papas-source
  • 1,221
  • 1
  • 14
  • 20