JavaScript - Test for an integer

前端 未结 11 2089
醉梦人生
醉梦人生 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.

提交回复
热议问题