patad patad - 2 years ago 175
Javascript Question

Check if string contains only digits

I want to check if a string contains only digits. I used this:

var isANumber = isNaN(theValue) === false;

if (isANumber){

.. but realized that it also allows + and -. Basically I wanna make sure the input contains ONLY digits and no other letters. Since +100 and -5 are both numbers, isNaN, is not the right way to go.
Perhaps a regexp is what I need? Any tips?

Answer Source

how about

var isnum = /^\d+$/.test(val);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download