I want that the text field only accept numeric values and spaces.
What is regular expression for this?
I was trying with \d+$
Thanks
Asked
Active
Viewed 1.1e+01k times
6 Answers
80
This one should work :
[0-9 ]+

Magus
- 14,796
- 3
- 36
- 51
-
26**OR also use with start and end string** `^[\d\s]+$` – Rohit Goyani May 20 '16 at 11:24
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
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 regular expression matches numbers with spaces, numbers without spaces, but not the spaces after all numbers
(\s*[0-9]+)+

baduga
- 233
- 1
- 8