Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS: regex for numbers and spaces?

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?

like image 305
matt Avatar asked Nov 05 '12 10:11

matt


3 Answers

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.

like image 133
nhahtdh Avatar answered Sep 30 '22 21:09

nhahtdh


Try

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

At least one number must be present for the above to succeed but please have a look at the regex example here

like image 42
Bruno Avatar answered Sep 30 '22 21:09

Bruno


Try

/^[\d ]*$/.test("238 238 45383")

console.log(/^[\d ]*$/.test("238 238 45383"));
like image 34
Kamil Kiełczewski Avatar answered Sep 30 '22 22:09

Kamil Kiełczewski