3

I have modal pop up for adding data, I have to validate textbox using JavaScript regular expression for numeric values only. I want to enter only numbers in text box, so tell me what is proper numeric regular expression for that?

Jakub Hampl
  • 36,560
  • 8
  • 70
  • 101
  • Is is integers only or do you want to have stuff like floats, rationals, scientific notation or complex? – Jakub Hampl Mar 24 '11 at 13:57
  • And, actually, I messed up the pattern. It should be `^\d+(?:\.\d+)?$` (The final * would allow `1.2.3.4`, which wouldn't be a valid number.) – Brad Christie Mar 24 '11 at 14:15
  • 1
    Jakob's question is worth repeating: What, exactly, is a "numeric value"? See: [What’s a Number?](http://stackoverflow.com/questions/4246077/simple-problem-with-regular-expression-only-digits-and-commas/4247184#4247184) – ridgerunner Mar 24 '11 at 17:24
  • Even better just put , but otherwise /^[0-9]$/ – Steve Tomlin Sep 10 '20 at 14:32

3 Answers3

2

Why not using isNaN ? This function tests if its argument is not a number so :

if (isNaN(myValue)) {
   alert(myValue + ' is not a number');
} else {
   alert(myValue + ' is a number');
}
Toto
  • 83,193
  • 59
  • 77
  • 109
  • 2
    isNAN will report a number for '0xabcd' since it is a valid hexadecimal number. – HBP Mar 24 '11 at 16:31
1

You can do it as simple as:

function hasOnlyNumbers(str) {
 return /^\d+$/.test(str);
}

Working example: http://jsfiddle.net/wML3a/1/

Martin Jespersen
  • 23,663
  • 6
  • 52
  • 66
0

^\d+$ of course if you want to specify that it has to be at least 4 digits long and not more than 20 digits the pattern would then be => ^\d{4,20}$

Jakub Hampl
  • 36,560
  • 8
  • 70
  • 101
pythonian29033
  • 4,817
  • 5
  • 29
  • 56