skip to Main Content

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?

3

Answers


  1. Chosen as BEST ANSWER

    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)
    

  2. 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

    Login or Signup to reply.
  3. 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).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search