Reputation: 431
Recently I'm working in a project, in which I need validate some mobile numbers according to mobile operator's codes. Here some examples:
01100000000
01500000000
01700000000
01800000000
01900000000
Now I want to validate, first 3 digits must be in (011,015,017,018,019) and next 8 characters must be digit and if user enter something like 0120000000 then the match will be false, cause valid operator code should be in (011,015,017,018,019).
Upvotes: 0
Views: 4358
Reputation: 179
You can use the following mobile number pattern:
Sample:
Regex.IsMatch("989373286128", @"^((((\+989)|(00989))|(09)|(989))(10|11|12|13|14|15|16|17|18|19|20|21|30|31|32|33|34|35|36|37|38|39|90))(\d{7})$")
Test:
+989103286128 -> Success
00989103286128 -> Success
989103286128 -> Success
+989773286128 -> Fail
009891032861282 -> Fail
GitHub:
I hope this help you.
Upvotes: 0
Reputation: 174696
Don't forget to add anchors in the regex while doing validations.
@"^(011|015|017|018|019)\d{8}$"
Reduced one,
@"^(01[15789])\d{8}$"
^
Asserts that we are at the start and $
asserts that we are at the end. \d{8}
matches exactly 8 digits.
Upvotes: 9
Reputation: 32266
Here's how you can do it without using regular expressions
string[] operatorCodes = new[] {"011", "015", "017", "018", "019"};
string number = "01100000000";
if (number.Length == 11
&& number.All(char.IsDigit)
&& operatorCodes.Any(number.StartsWith))
{
// Valid mobile number.
}
Upvotes: 1
Reputation: 10708
you can group symbols in a regex with ()
, and use |
for "or", thus
(011|015|017|018|019)[0-9]{8}
Upvotes: 0