Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for parsing and validating mobile number

I wonder what the best practice for parsing and validating a mobile number before sending a text is. I've got code that works, but I'd like to find out better ways of doing it (as my last question, this is part of my early new years resolution to write better quality code!).

At the moment we are very forgiving when the user enters the number on the form, they can enter things like "+44 123 4567890", "00441234567890", "0123456789", "+44(0)123456789", "012-345-6789" or even "haven't got a phone".

However, to send the text the format must be 44xxxxxxxxxx (this is for UK mobiles only), so we need to parse it and validate it before we can send. Below is the code that I have for now (C#, asp.net), it would be great if anyone had any ideas on how to improve it.

Thanks,

Annelie

private bool IsMobileNumberValid(string mobileNumber)
    {
        // parse the number
        _mobileNumber = ParsedMobileNumber(mobileNumber);

        // check if it's the right length
        if (_mobileNumber.Length != 12)
        {
            return false;
        }

        // check if it contains non-numeric characters
        if(!Regex.IsMatch(_mobileNumber, @"^[-+]?[0-9]*\.?[0-9]+$"))
        {
            return false;
        }

        return true;
    }

    private string ParsedMobileNumber(string number)
    {
        number = number.Replace("+", "");
        number = number.Replace(".", "");
        number = number.Replace(" ", "");
        number = number.Replace("-", "");
        number = number.Replace("/", "");
        number = number.Replace("(", "");
        number = number.Replace(")", "");

        number = number.Trim(new char[] { '0' });

        if (!number.StartsWith("44"))
        {
            number = "44" + number;
        }

        return number;
    }

EDIT

Here's what I ended up with:

private bool IsMobileNumberValid(string mobileNumber)
    {
        // remove all non-numeric characters
        _mobileNumber = CleanNumber(mobileNumber);

        // trim any leading zeros
        _mobileNumber = _mobileNumber.TrimStart(new char[] { '0' });

        // check for this in case they've entered 44 (0)xxxxxxxxx or similar
        if (_mobileNumber.StartsWith("440"))
        {
            _mobileNumber = _mobileNumber.Remove(2, 1);
        }

        // add country code if they haven't entered it
        if (!_mobileNumber.StartsWith("44"))
        {
            _mobileNumber = "44" + _mobileNumber;
        }

        // check if it's the right length
        if (_mobileNumber.Length != 12)
        {
            return false;
        }

        return true;
    }

    private string CleanNumber(string phone)
    {
        Regex digitsOnly = new Regex(@"[^\d]");
        return digitsOnly.Replace(phone, "");
    }
like image 960
annelie Avatar asked Dec 30 '10 14:12

annelie


People also ask

How do I validate a phone number input?

Validate a Phone Number Using a JavaScript Regex and HTMLfunction validatePhoneNumber(input_str) { var re = /^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/; return re. test(input_str); } function validateForm(event) { var phone = document.

What is the best way to validate a telephone number in your application in Java?

Mobile number validation in Java is done using Pattern and Matcher classes of Java. The pattern class is used to compile the given pattern/regular expression and the matcher class is used to match the input string with compiled pattern/regular expression.

How do I validate a phone number in Salesforce?

US Phone Number Has Ten Digits Validates that the Phone number is in (999) 999-9999 format. This works by using the REGEX function to check that the number has ten digits in the (999) 999-9999 format. Error Message: US phone numbers should be in this format: (999) 999-9999.


2 Answers

Use a regular expression to remove any non-numeric characters instead of trying to guess how a person will enter their number - this will remove all your Replace() and Trim() methods, unless you really need to trim a leading zero.

string CleanPhone(string phone)
{
    Regex digitsOnly = new Regex(@"[^\d]");   
    return digitsOnly.Replace(phone, "");
}

Alternatively, I would recommend you use a masked textbox to collect the # (there are many options available) to allow only numeric input, and display the input with whatever format you'd like. This way you're guaranteeing that the value received will be all numeric characters.

like image 92
Keith Avatar answered Nov 03 '22 01:11

Keith


Check out QAS, it's a commercial solution.

They have email, phone and address validations.

http://www.qas.com/phone-number-validation-web-service.htm

We use their services for Address and Email (not phone) and have been satisfied with it.

like image 29
turtlepick Avatar answered Nov 03 '22 00:11

turtlepick