Check string for integer

I want to check the input field. The user must enter a telephone number with a minimum length of 10 digits.

Therefore, I need to check illegal characters. It would be nice to verify that the input is an integer or not.

I came up with this, but it does not work (n will be a string).

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

Any ideas?

+4
source share
5 answers

You can run the test as follows:

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

This will fail if there are no digits in the string, or if the string length is less than 10 characters

+12
source

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 problem: Check decimal numbers in JavaScript - IsNumeric ()

+3
source

This may be superfluous, but Google recently announced a library to test the phone. Java and Javascript options are available.

+1
source

Checking the phone number is a bit more complicated than checking if the input is integer. As an example, phone numbers can start with zeros, so it's neither technically nor int. Also, users can enter a dash: For example:

 00 34 922-123-456 

So, with regard to verification, you have several options:

  • Use regex expression to check, look:

    http://regexlib.com/

    This site will contain hundreds of examples.

  • Use a loop to check each character in turn, i.e. is an int or dash

I would recommend the former, as the latter depends on sequential input from users, and you will not get this

+1
source

Why not use:

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

How to return to your function?

this is the result 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 
0
source

Source: https://habr.com/ru/post/1335555/


All Articles