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?
            Asked
            
        
        
            Active
            
        
            Viewed 1,190 times
        
    3
            
            
        - 
                    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
- 
                    1Jakob'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 Answers
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
        
- 89,455
- 62
- 89
- 125
- 
                    2isNAN 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
        
- 25,743
- 8
- 56
- 68
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
        
- 39,863
- 10
- 77
- 106
 
    
    
        pythonian29033
        
- 5,148
- 5
- 31
- 56
