Search code examples
javascriptregexmongooseregex-groupregex-greedy

Validate phone number in two different formats in Mongoose schema


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?


Solution

  • 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).