1

I have the follwing code in PHP:

if(is_numeric($first_name[0]) === true){
   //Do something
}

How would I be able to do the same check using JavaScript? I also would like to get a PHP script to check if there is a number in $first_name at all, as I don't want the user to add a number in their first or last names please?

Willem
  • 123
  • 9
  • 2
    Do you want to check if the value is a number type (e.g. `3`), or a string that contains numbers (e.g. `"john3"`), or a string or number that is a "valid" number (e.g. `2.3` or `"2.3"`)? – RobG Aug 07 '13 at 22:45

5 Answers5

1

Use regular expressions.

if (/-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/.test(yourInput)) {
   // Do something
}

Of course, this will only work on strings. For a different method, see a duplicate question:

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

To only check if the input contains a number (0-9) at all, regex works again:

if (/[0-9]+/.test(yourInput)) {
   // Do something
}
Community
  • 1
  • 1
Matt Bryant
  • 4,841
  • 4
  • 31
  • 46
  • That doesn't check "if there is a number in $first_name at all", it checks if it's only digits. – RobG Aug 07 '13 at 22:47
  • He wants a javascript alternative to `is_numeric`, which the docs say "Finds whether the given variable is numeric. Numeric strings consist of optional sign, any number of digits, optional decimal part and optional exponential part." – Matt Bryant Aug 07 '13 at 22:50
  • The first does not the same thing as PHP's `is_numeric` and your edit is just a [copy pasta of @Lochemage's answer](http://stackoverflow.com/a/18115091/508666) – PeeHaa Aug 07 '13 at 22:53
  • I dug up code I used for integer validation a while back that should actually meet the criteria. And I did link to that question for a reason. Edit - I see what you're saying. Apparently we found the same link. – Matt Bryant Aug 07 '13 at 22:58
  • 2
    @MattBryant—it's not clear to me what the OP wants. :-/ – RobG Aug 08 '13 at 01:38
1

in js to check if the number variable is a number:

isFinite(number) && !isNaN(parseFloat(number))
Kirill Ivlev
  • 12,310
  • 5
  • 27
  • 31
1

Something I found here:

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}
Community
  • 1
  • 1
Lochemage
  • 3,974
  • 11
  • 11
0

If the variable in question is $first_name

if( $first_name && !isNaN($first_name[0])) {

    // do something
}
Sushanth --
  • 55,259
  • 9
  • 66
  • 105
0

If you want to check whether *$first_name* contains any digits, then:

if (/\d/.test($first_name)) {
    // $first_name contains at least one digit
}
RobG
  • 142,382
  • 31
  • 172
  • 209