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?

4
  • Is is integers only or do you want to have stuff like floats, rationals, scientific notation or complex? Commented Mar 24, 2011 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.) Commented Mar 24, 2011 at 14:15
  • 1
    Jakob's question is worth repeating: What, exactly, is a "numeric value"? See: What’s a Number? Commented Mar 24, 2011 at 17:24
  • Even better just put <input type="number">, but otherwise /^[0-9]$/ Commented Sep 10, 2020 at 14:32

3 Answers 3

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');
}
Sign up to request clarification or add additional context in comments.

1 Comment

isNAN will report a number for '0xabcd' since it is a valid hexadecimal number.
1

You can do it as simple as:

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

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.