-1

The phone number I need to validate needs to be at least 8 characters long and has two possible formats:

  1. Must be at least 8 digits like "12345678"

    OR

  2. Must have 2 or 3 digits before "-" and 6 or more digits after "-"

I need to solve this using a regex.

I have tried this but it doesn't seem to work properly (1-22334455) gets accepted even though I want it to be rejected.

number: {
    type: String,
    minLength: 8,
    validate: {
        validator: v => /\d{2,3}-\d{6,}/.test(v) || /\d{8,}/.test(v),
        message: "this is not a valid number"
    }
}

Another attempt (still doesn't quite do it):

number: {
    type: String,
    minLength: 8,
    validate: {
        validator: v => /\d{2,3}-?\d{6,}/.test(v),
        message: "this is not a valid number"
    }
}

How can I improve it?

MoonGoose
  • 19
  • 4

3 Answers3

1

You might use

^(?:\d{8,}|\d{2,3}-\d{6,})$

Explanation

  • ^ Start of string
  • (?: Non capture group for the alternatives
    • \d{8,} Match 8 or more digits
    • | or
    • \d{2,3}-\d{6,} Match 2-3 digits, - and 6 or more digits
  • ) Close the non capture group
  • $ End of strirng

Regex demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70
1

In your first solution, you have to add a constrain on the start and ending of the string, with ^ and $. That's why 1-22334455 get captured in both solution (in the 2nd solution, it is due to the -? section).

accactus
  • 26
  • 4
1

This was finally the answer: Thank you everyone for your feedback I really appreciate it. I missed the ^ at the beginning and $ at the end.

/^\d{2,3}-\d{6,}$/.test(v) || /^\d{8,}$/.test(v)
MoonGoose
  • 19
  • 4