40

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,124
  • 3
  • 15
  • 38

6 Answers6

80

This one should work :

[0-9 ]+
Magus
  • 14,796
  • 3
  • 36
  • 51
19

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

^[\d ]*$

Dmitrii Dovgopolyi
  • 6,231
  • 2
  • 27
  • 44
  • 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,334
  • 20
  • 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

Daniel Cambría
  • 217
  • 1
  • 6
3

This should work.

/^[0-9\s]*$/
Pika Supports Ukraine
  • 3,612
  • 10
  • 26
  • 42
Julian W.
  • 1,501
  • 7
  • 20
3

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

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