-1

I am trying to make a simple phone number validation and I struggle with regex validation for that. I would like to allow users input the following:

  1. Any digit
  2. -
  3. +
  4. (
  5. )
  6. space/white space

At the moment I have something like this: /[0-9-+()\s]*/im, but it doesn't seem to work. Can someone help me out? I am not targeting any specific country, therefore I don't want to follow any strict formats.

2-D
  • 23
  • 7
  • Escape `-` by prepending a backslash or move it to an end. – revo May 26 '20 at 05:05
  • 1
    Does this answer your question? [Validate phone number with JavaScript](https://stackoverflow.com/questions/4338267/validate-phone-number-with-javascript) – Always Learning May 26 '20 at 05:06
  • Many characters need escaping. \+ \- \( \) – QuentinUK May 26 '20 at 05:06
  • @AlwaysLearning, no, it targets specific format for a country. I tried escaping all characters, but still no luck `/[0-9\-\+\(\)\s]*/im` – 2-D May 26 '20 at 05:10
  • Show the code.. – revo May 26 '20 at 05:11
  • @revo, I got something like this. A custom `Field` component which has validator: validator: value => { if (value) { /[0-9\-\+\(\)\s]*$/.test(value); } }, – 2-D May 26 '20 at 05:24
  • Show us whatever you have. – revo May 26 '20 at 05:24
  • One problem is if the user enter 123xyz it will pass that because 123 is valid. Even xyz will pass the test because * means zero length match. You can enclose with ^$. (No need for i case insensitive or multiline phone numbers) /^[0-9\+\-\(\)\s]*$/ – QuentinUK May 26 '20 at 05:32
  • 1
    @QuentinUK No need to escape `+` or parentheses inside a bracket expression. Also if OP is using some kind of validations like in angular then regex shouldn't be enclosed in `^` or `$` anchors. OP has to show the code. – revo May 26 '20 at 05:59

1 Answers1

0

You need to start with the ^ character to force it to match from the start, and the $ character to force it to match to the end. Otherwise it will match what it can and ignore anything that doesn't match outside of that. You can also be more directive with it. For example a + character might only be allowed as the first character, or you might want to enforce that there are at least 7 characters. The example code below shows some of that.

// r1 fixes the one you were trying by adding ^ and $ 
const r1 = /^[-+0-9()\s]*$/
//          =            =

// r2 adds rules like a "+" can only appear at the start
// and there must be at least 7 digits
const r2 = /^\+?[-0-9()\s]{7,}$/
//           ===          ====

const tests = [
  "123 456-7890", 
  "789", 
  "+4 9084342",
  "hello",
  "123+457+432",
  "1234567!"
]
for (const num of tests) console.log(`r1: ${r1.test(num)} - ${num}`)
console.log("-----")
for (const num of tests) console.log(`r2: ${r2.test(num)} - ${num}`)
Always Learning
  • 5,510
  • 2
  • 17
  • 34