JS: regex for numbers and spaces?

matt picture matt · Nov 5, 2012 · Viewed 19.3k times · Source

I'm using happyJS and use the regex underneath for phone validation

phone: function (val) {
        return /^(?:[0-9]+$)/.test(val);
    }

However this ONLY allows numbers. I want the user to be able to enter spaces as well like

238 238 45383

Any idea why return /^(?:[0-9 ]+$)/.test(val); is not doing the trick?

Answer

nhahtdh picture nhahtdh · Nov 5, 2012

This is my suggested solution:

/^(?=.*\d)[\d ]+$/.test(val)

The (?=.*\d) asserts that there is at least one digit in the input. Otherwise, an input with only blank spaces can match.

Note that this doesn't put any constraint on the number of digits (only makes sure there are at least 1 digit), or where the space should appear in the input.