The phone number I need to validate needs to be at least 8 characters long and has two possible formats:
-
Must be at least 8 digits like "12345678"
OR
-
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
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.
You might use
Explanation
^
Start of string(?:
Non capture group for the alternativesd{8,}
Match 8 or more digits|
ord{2,3}-d{6,}
Match 2-3 digits,-
and 6 or more digits)
Close the non capture group$
End of strirngRegex demo
In your first solution, you have to add a constrain on the start and ending of the string, with
^
and$
. That’s why1-22334455
get captured in both solution (in the 2nd solution, it is due to the-?
section).