Deepanjali Patole
Deepanjali Patole

Reputation: 29

Regular expression JavaScript

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?

Upvotes: 3

Views: 1191

Answers (3)

Toto
Toto

Reputation: 91375

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');
}

Upvotes: 2

pythonian29033
pythonian29033

Reputation: 5207

^\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}$

Upvotes: 0

Martin Jespersen
Martin Jespersen

Reputation: 26183

You can do it as simple as:

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

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

Upvotes: 1

Related Questions