34

I want that the text field only accept numeric values and spaces. What is regular expression for this? I was trying with \d+$ Thanks

Diboliya
  • 1,026
  • 3
  • 13
  • 36

6 Answers6

74

This one should work :

[0-9 ]+
Magus
  • 14,245
  • 3
  • 37
  • 48
15

^ for the begining of string. [\d ]* for any combination of this symbols. $ for end of string.

^[\d ]*$

Dmitrii Dovgopolyi
  • 6,027
  • 1
  • 26
  • 42
  • I wouldn't consider a string with 0 occurrences of numeric values/spaces a string consisting of numeric values/spaces. – Michael Dec 20 '12 at 13:35
  • 1
    . That means it does not accept any symbol besides numeric values and spaces. That means that empty string does not violate the condition – Dmitrii Dovgopolyi Dec 20 '12 at 13:43
  • for example if you need to validate user input, you should not write an error, when user have not started to write anything or just deleted all he wrote. – Dmitrii Dovgopolyi Dec 20 '12 at 13:46
  • Huh? The text field could be empty. If the user hit submit and the text box was empty, your regex would match the empty string. – Michael Dec 20 '12 at 13:47
  • How do you know in what context he is using this in? It could be for form validation after Submit has already been clicked. – Michael Dec 20 '12 at 13:48
  • 1
    and could be not. so my assumption is as true as yours. – Dmitrii Dovgopolyi Dec 20 '12 at 14:52
6

You're going to want to use [0-9 ]+

Michael
  • 3,294
  • 19
  • 27
3

If you want to match only the numbers, use:

(\b\d+)/g or (\b[0-9]+)/g

where:
\b will match borders
\d or [0-9] match numbers
+ will match 1 or more times \d (or [0-9])
/g turns on global mode, to match the regex many times

2

This should work.

/^[0-9\s]*$/
Pika Supports Ukraine
  • 3,394
  • 9
  • 24
  • 41
Julian Lin
  • 1,311
  • 5
  • 17
0

This regular expression matches numbers with spaces, numbers without spaces, but not the spaces after all numbers

(\s*[0-9]+)+
baduga
  • 193
  • 8