Sushant Sangle
Sushant Sangle

Reputation: 53

Combine regex for mobile number validation

Scenario: Front end validation - Mobile number Must be numeric, must start with '02', have at least 8? numeric characters, limited to 13? numeric characters

Examples:

MSISDN errorMessage 021123 Please enter a valid Vodafone mobile number, 091234567 Please enter a valid Vodafone mobile number, 02112345678910 Please enter a valid Vodafone mobile number, abcdefghijkl Please enter a valid Vodafone mobile number, 021$123456 Please enter a valid Vodafone mobile number

Also, the format for the number should be 021 055555 when I enter the number in the input field. space after the first three numbers.

can anyone help me form a regex for such kind of example?

Upvotes: 0

Views: 279

Answers (2)

OliverRadini
OliverRadini

Reputation: 6476

I believe this regex would perform the match you need:

const numbers = [
  "023 45678901",
  "023 456789012",
  "023 4567890123",
  "033 45678901",
  "013 45678901",
  "013 45",
  "013 45678901234567",
]

const numberIsValid = number => !!number.match(/02\d\s\d{5,10}/)

console.dir(numbers.map(numberIsValid))

Here is what each part of the regex is doing:

02 matches the characters 02 literally (case sensitive)

\d matches a digit (equal to [0-9])

\s matches any whitespace character (equal to [\r\n\t\f\v ])

\d{5,10} matches a digit (equal to [0-9])

{5,10} Quantifier — Matches between 5 and 10 times, as many times as possible, giving back as needed (greedy)

Upvotes: 1

Sankalp Sharma
Sankalp Sharma

Reputation: 577

Something of this sort would help

input.match(/^02[0-9]{6,11}$/)

Explanation: input is obviously the input. ^ ensures that this is where the string to be matched begins. [0-9] means the subsequent characters must be between 0 and 9, and {6-11} means that these characters can be repeated between 6 and 11 times. $ at the end indicates that this is where the string must end.

Upvotes: 0

Related Questions