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?
3 Answers
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');
}
1 Comment
HBP
isNAN will report a number for '0xabcd' since it is a valid hexadecimal number.
You can do it as simple as:
function hasOnlyNumbers(str) {
return /^\d+$/.test(str);
}
Working example: http://jsfiddle.net/wML3a/1/
^\d+(?:\.\d+)?$(The final * would allow1.2.3.4, which wouldn't be a valid number.)