Reputation: 44293
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?
Upvotes: 11
Views: 25292
Reputation: 1388
You can try the below regex for checking numbers and spaces.
function isTextAndNumberSpaceOnly(text) {
var regex = /^[0-9 ]+$/;
if (regex.test(text)) {
return true;
} else {
return false;
}
}
Upvotes: 1
Reputation: 92347
Try
/^[\d ]*$/.test("238 238 45383")
console.log(/^[\d ]*$/.test("238 238 45383"));
Upvotes: 1
Reputation: 37
Personally I use this code and it works properly:
function validateMobile(mob)
{
var re = /^09[0-9]{9}$/
if(mob.match(re))
return true;
else
return false;
}
Upvotes: 0
Reputation: 5822
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
Upvotes: 6
Reputation: 56809
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.
Upvotes: 10