JavaScript - Test for an integer

前端 未结 11 2095
醉梦人生
醉梦人生 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条回答
  •  猫巷女王i
    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.

提交回复
热议问题