SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    Guru in training bronze trophy SoulScratch's Avatar
    Join Date
    Apr 2006
    Location
    Maryland
    Posts
    1,838
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Validate number function

    I have a function to check if a string (say the value of an input element) is a valid number. By valid number (I'm not a math whiz or anything) I mean something like -9999, 55000, 1.223523, 1.5. Something like '-9999LETTER' or 'l123494' would not be valid.

    If I combined parseFloat and isNaN, with something like..

    var isNumber = function(str) {
    if (isNaN(parseFloat(str))) { return false; }
    else { return true; }
    }

    Then parseFloat would obviously only extract the numbers from the string. Therefore if I did isNumber('555555555rrrrrrrrrrrrr') I would get a return value of true, since it only extracts the 555555555 via parseFloat, but the value ITSELF is not a valid number because of the r's.

    Then I heard of the subtraction of zero to force it to be a number and changed my function like so...

    var isNumber = function(str) {
    if (isNaN(str-0)) { return false;}
    else {return true;}
    }

    Edit:
    Just optimized it so it would be a one-liner

    function isNumber(str) { return !isNaN(str-0) }

    isNumber('5555555555rrrrrrrr') would now return false which is exactly what I want.

    I'm just wondering if there are any quirks there may be of my new function that subtractions 0 to try to convert it into a number or if there are any better ways of doing it.

    Thanks.

  2. #2
    SitePoint Wizard siteguru's Avatar
    Join Date
    Oct 2002
    Location
    Scotland
    Posts
    3,631
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    str * 1 does the same thing ... if the str is not a number then the product is NaN, hence isNaN = true.
    Ian Anderson
    www.siteguru.co.uk

  3. #3
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)
    Instead of using those hacks, properly cast the value to a number instead. If it's not a proper number it will return NaN.

    The other benefit is the code becomes more unstastandable.

    Code Javascript:
    function isNumber(str) { return !isNaN(Number(str)) }
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •