JavaScript - Test for an integer

前端 未结 11 1927
醉梦人生
醉梦人生 2020-12-02 11:17

I have a text field that allows a user to enter their age. I am trying to do some client-side validation on this field with JavaScript. I have server-side validation already

相关标签:
11条回答
  • 2020-12-02 11:37

    I found the NaN responses lacking because they don't pick up on trailing characters (so "123abc" is considered a valid number) so I tried converting the string to an integer and back to a string, and ensuring it matched the original after conversion:

    if ("" + parseInt(stringVal, 10) == stringVal) { alert("is valid number"); }
    

    This worked for me, up until the numbers were so large they started appearing as scientific notation during the conversion.

    ...so of course this means you could enter a number in scientific notation, but checking minimum and maximum values as well would prevent that if you so desire.

    It will of course fail if you use separators (like "1,000" or "1.000" depending on your locale) - digits only allowed here.

    0 讨论(0)
  • 2020-12-02 11:38
    If (enteredAge < "1" || enteredAge > "130") ......
    

    Simple and it works....until they develop immortality

    0 讨论(0)
  • 2020-12-02 11:42
    var intRegex = /^\d+$/;
    if(intRegex.test(someNumber)) {
       alert('I am an int');
       ...
    }
    

    That will absolutely, positively fail if the user enters anything other than an nonnegative integer.

    0 讨论(0)
  • 2020-12-02 11:47

    For real int checking, use this:

    function isInt(value) { 
        return !isNaN(parseInt(value,10)) && (parseFloat(value,10) == parseInt(value,10)); 
    }
    

    The problem with many int checks is that they return 'false' for 1.0, which is a valid integer. This method checks to make sure that the value of float and int parsing are equal, so for #.00 it will return true.

    UPDATE:

    Two issues have been discussed in the comments I'll add to the answer for future readers:

    • First, when parsing string values that use a comma to indicate the decimal place, this method doesn't work. (Not surprising, how could it? Given "1,001" for example in the US it's an integer while in Germany it isn't.)
    • Second, the behavior of parseFloat and parseInt has changed in certain browsers since this answer was written and vary by browser. ParseInt is more aggressive and will discard letters appearing in a string. This is great for getting a number but not so good for validation.

    My recommendation and practice to use a library like Globalize.js to parse numeric values for/from the UI rather than the browser implementation and to use the native calls only for known "programmatically" provided values, such as a string parsed from an XML document.

    0 讨论(0)
  • 2020-12-02 11:47

    use isNaN(n)

    i.e.

    if(isNaN(intValue))

    in place of

    if (intValue == Number.NaN)
    0 讨论(0)
提交回复
热议问题