Skip to content
Advertisement

Regex for numbers with spaces and + sign in front

If i want to accept only numbers then i will use this regex

^[0-9]*$

but the problem here is that the numbers like

+1 00

are not catched and my regex will show that it is invalid

The user needs to type only numbers but only one space in between is allowed and + sign at the beggining should be optional.

So acceptable is:

+1 11 1 1 11 
or
1 11 1 1 11 

Unacceptable is:

+1    11 1 1 11
or
1 11     1 1 11 

please help

Advertisement

Answer

You may try using this regex pattern:

^+?d+(?:[ ]?d+)*$

Sample script:

console.log(/^+?d+(?:[ ]?d+)*$/.test('+1 11 1 1 11')); // true

console.log(/^+?d+(?:[ ]?d+)*$/.test('1 11 1 1 11'));  // true

console.log(/^+?d+(?:[ ]?d+)*$/.test('+1    11 1 1 11')); // false

console.log(/^+?d+(?:[ ]?d+)*$/.test('1 11    1 1 11'));  // false

The regex pattern used here says to:

^                 from the start of the string
    +?           match an optional leading +
    d+           then match one or more digits
    (?:[ ]?d+)*  followed by an optional single space and more digits,
                  zero or more times
$                 end of the string
Advertisement