tuta4
tuta4

Reputation: 79

Regexp for phone numbers

I'd like to create a regular expression based attribute for my ASP.NET website to check if the specified phone number is valid or not. It has to let through the patterns like these:

+3630 1234 567

06 30 1234 567

0630 1234 567

061 123 456

06 1 123 456

So, the most important thing is that the first character can be a '+', but this is not a requirement and after that only numbers and white spaces.

I've tried the following, but no luck with it.

public class PhoneNumberAttribute : RegularExpressionAttribute
{
    public PhoneNumberAttribute()
        :base(@"^\+?[0-9 ]")
    { }
}

Upvotes: 1

Views: 113

Answers (2)

Jeremy Bell
Jeremy Bell

Reputation: 718

You could try libphonenumber - https://github.com/erezak/libphonenumber-csharp

Upvotes: 0

Jerry
Jerry

Reputation: 71538

Your regex currently accepts an optional + sign at the beginning of the string (which is good so far), but only one digit or space. You need to allow more digits/spaces and to do this, you add a quantifier. A good one to use here is the + quantifier which means one or more:

^\+?[0-9 ]+

Now, it will also accept other characters, so add an end of line anchor as well so that the regex checks the whole string:

^\+?[0-9 ]+$

That should do it. If you have more rules though (such as no consecutive spaces, limited number of digits, etc), the regex will have to be revised.

Upvotes: 3

Related Questions