515

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 want to make sure an input contains ONLY digits and no other characters. Since +100 and -5 are both numbers, isNaN() is not the right way to go. Perhaps a regexp is what I need? Any tips?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
patad
  • 9,364
  • 11
  • 38
  • 44

15 Answers15

1024

how about

let isnum = /^\d+$/.test(val);
Syntle
  • 5,168
  • 3
  • 13
  • 34
Scott Evernden
  • 39,136
  • 15
  • 78
  • 84
97
string.match(/^[0-9]+$/) != null;
Jason S
  • 184,598
  • 164
  • 608
  • 970
24
String.prototype.isNumber = function(){return /^\d+$/.test(this);}
console.log("123123".isNumber()); // outputs true
console.log("+12".isNumber()); // outputs false
balupton
  • 47,113
  • 32
  • 131
  • 182
  • 11
    It's considered bad practice in Javascript to modify prototypes of built-in objects (principle of least surprise, and potential conflicts in future ECMA versions) - consider `isNumber = () => /^\d+$/.test(this);` instead, and use as `console.log(isNumber("123123));` – Nick Bull Sep 05 '19 at 11:04
  • 7
    FWIW, in 2009 when this answer was posted, it was not yet considered a bad practice. Several jQuery competitors that existed then, before jQuery had yet to win out, all practiced prototype extensions. – balupton Sep 07 '19 at 17:38
  • still, it was a bad practice, even though it wasn't considered as such by jQuery lovers. – Sergei Kovalenko Apr 04 '23 at 09:05
21

If you want to even support for float values (Dot separated values) then you can use this expression :

var isNumber = /^\d+\.\d+$/.test(value);
Adithya Sai
  • 1,592
  • 2
  • 19
  • 33
  • however if you don't use a float rather int it will return false maybe using "?" after ".\" solved that. I suggest this /^\d+[\.,\,]?\d+$/.test(value) to allow both comma and point decimal (later maybe can transform comma to point) – Lucke Oct 19 '17 at 23:54
  • 2
    @Lucke, the regex you suggested will only be able to find numbers with a decimal or higher than 9. If you change the first `\d+` to `\d*?`, it will be able to match 0 - 9, as well as numbers such as .333 – Gust van de Wal Dec 19 '17 at 19:29
  • 7
    Close: ```var isNumber = /^\d*\.?\d+$/.test(value)``` -- matches '3.5', '.5', '3' -- does not match '3.' – Peter Hollingsworth Jul 18 '18 at 20:23
  • Since 2009, this question was always asking how to validate that a string contains only numbers. This post is the correct answer to a different question. – mickmackusa Jul 21 '21 at 17:41
  • 1
    @PeterHollingsworth This doesn't match negative numbers like `-100.2` – dewey Apr 04 '22 at 10:01
18

Here's another interesting, readable way to check if a string contains only digits.

This method works by splitting the string into an array using the spread operator, and then uses the every() method to test whether all elements (characters) in the array are included in the string of digits '0123456789':

const digits_only = string => [...string].every(c => '0123456789'.includes(c));

console.log(digits_only('123')); // true
console.log(digits_only('+123')); // false
console.log(digits_only('-123')); // false
console.log(digits_only('123.')); // false
console.log(digits_only('.123')); // false
console.log(digits_only('123.0')); // false
console.log(digits_only('0.123')); // false
console.log(digits_only('Hello, world!')); // false
Grant Miller
  • 27,532
  • 16
  • 147
  • 165
  • 1
    This will also return `true` for empty string `''`, and an empty array `[]`, an array of integers `[1, 2, 3]` (once they are < 10). It's more prone to bugs/misuse than the basic regular expression `/^\d+$/` I think – Drenai Dec 08 '19 at 16:15
  • 3
    This is far easier to read than a Regex, and is easily expandable to other approaches. When used in TypeScript, and in conjunction with length checks, this can be very elegant. – krillgar Feb 24 '21 at 13:32
  • 1
    I like its uniqueness, but also, this solution is most “resource consuming“ to use and not scalable in performance intensive or data heavy client-side, due to requiring 10x operations for every character of input. – KingJulian May 03 '22 at 07:31
11

Here is a solution without using regular expressions:

function onlyDigits(s) {
  for (let i = s.length - 1; i >= 0; i--) {
    const d = s.charCodeAt(i);
    if (d < 48 || d > 57) return false
  }
  return true
}

where 48 and 57 are the char codes for "0" and "9", respectively.

ingdc
  • 760
  • 10
  • 16
10

This is what you want

function isANumber(str){
  return !/\D/.test(str);
}
8

in case you need integer and float at same validation

/^\d+\.\d+$|^\d+$/.test(val)

Leandro Menezes
  • 103
  • 1
  • 4
  • Since 2009, this question was always asking how to validate that a string contains only numbers. This post is the correct answer to a different question. – mickmackusa Jul 21 '21 at 17:42
5
function isNumeric(x) {
    return parseFloat(x).toString() === x.toString();
}

Though this will return false on strings with leading or trailing zeroes.

Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129
Peter Hollingsworth
  • 1,870
  • 1
  • 18
  • 18
4

Well, you can use the following regex:

^\d+$
Joey
  • 344,408
  • 85
  • 689
  • 683
  • Does not work for floating point numbers. – myverdict Jun 05 '23 at 00:34
  • 1
    Well, floating point numbers don't only contain digits. They may very well also include a decimal point. And since the question was about digits instead of things that can be parsed as a number, the answer stands. – Joey Jun 05 '23 at 06:34
1

if you want to include float values also you can use the following code

theValue=$('#balanceinput').val();
var isnum1 = /^\d*\.?\d+$/.test(theValue);
var isnum2 =  /^\d*\.?\d+$/.test(theValue.split("").reverse().join(""));
alert(isnum1+' '+isnum2);

this will test for only digits and digits separated with '.' the first test will cover values such as 0.1 and 0 but also .1 , it will not allow 0. so the solution that I propose is to reverse theValue so .1 will be 1. then the same regular expression will not allow it .

example :

 theValue=3.4; //isnum1=true , isnum2=true 
theValue=.4; //isnum1=true , isnum2=false 
theValue=3.; //isnum1=flase , isnum2=true 
anouar es-sayid
  • 355
  • 5
  • 11
  • Since 2009, this question was always asking how to validate that a string contains only numbers. This post is the correct answer to a different question. – mickmackusa Jul 21 '21 at 17:43
0

If you use jQuery:

$.isNumeric('1234'); // true
$.isNumeric('1ab4'); // false
Jacob
  • 3,598
  • 4
  • 35
  • 56
0

Here's a Solution without using regex

const  isdigit=(value)=>{
    const val=Number(value)?true:false
    console.log(val);
    return val
}

isdigit("10")//true
isdigit("any String")//false
0

If you want to leave room for . you can try the below regex.

/[^0-9.]/g
Appu Mistri
  • 768
  • 8
  • 26
-2
c="123".match(/\D/) == null #true
c="a12".match(/\D/) == null #false

If a string contains only digits it will return null

Lakhani Aliraza
  • 435
  • 6
  • 8