parseInt always returns NaN?

后端 未结 4 613
太阳男子
太阳男子 2020-12-06 12:48

long story short, i was trying to validate a phone field. ive added the isNaN and parseInt for checking the \" \" in the field but tha

相关标签:
4条回答
  • 2020-12-06 13:13

    parseInt only returns NaN if the first character cannot be converted to a number.

    https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt

    0 讨论(0)
  • 2020-12-06 13:15

    Various ways to coerse JS strings to numbers, and their consequences:


    (source: phrogz.net)

    I personally use *1 as it is short to type, but still stands out (unlike the unary +), and either gives me what the user typed or fails completely. I only use parseInt() when I know that there will be non-numeric content at the end to ignore, or when I need to parse a non-base-10 string.

    Edit: Based on your comment, if using phone.val() fixed it then

    1. You were using jQuery (which you never mentioned, and should have), and
    2. You actually had/have a jQuery object, wrapping one or more DOM elements (probably just one).

    Whenever you do var foo = $('…'); then the foo variable references a jQuery object of one or more elements. You can get the first actual DOM element from this via var fooEl = foo[0]; or var fooEl = foo.get(0);…but even then you still have a DOM element and not a particular property of that.

    For form inputs, you need to get the .value from the DOM element, which is what the jQuery .val() method does.

    0 讨论(0)
  • 2020-12-06 13:16

    parseInt is a bit odd at times:

    > parseInt("123-456-789")
    123
    

    Fortunately you can probably solve your case with:

    > Number("123-456-789")
    NaN
    
    0 讨论(0)
  • 2020-12-06 13:18

    I've seen Number() suggested, but that will still allow things like -21 or 123.456. The best way to check for the absence of non-digits in a string is like this:

    function hasNonDigit(str){
      return /\D/g.test(str.toString());
    }
    
    console.log(hasNonDigit("123-456-7890"));
    console.log(hasNonDigit("1234567890"));

    0 讨论(0)
提交回复
热议问题