JS: regex for numbers and spaces?

I use happyJS and use regex to test the phone

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, e.g.

 238 238 45383 

Any idea why return /^(?:[0-9 ]+$)/.test(val); does not work?

+5
source share
4 answers

This is my suggested solution:

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

(?=.*\d) states that there is at least one digit at the input. Otherwise, the input with spaces may match.

Please note that this does not place any limit on the number of digits (just to make sure that they are at least 1 digit) or where space should appear at the input.

+7
source

Try

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

To achieve the above result, at least one number must be present, but please take a look at the example regex example

+4
source

Personally, I use this code and it works correctly:

 function validateMobile(mob) { var re = /^09[0-9]{9}$/ if(mob.match(re)) return true; else return false; } 
0
source

Try

 /^[0-9 ]*$/.test("238 238 45383") 

 console.log(/^[0-9 ]*$/.test("238 238 45383")); 

0
source

Source: https://habr.com/ru/post/1444072/


All Articles