Best practice for parsing and validating mobile number

17,024

Solution 1

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.

Solution 2

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.

Share:
17,024
annelie
Author by

annelie

Updated on July 21, 2022

Comments

  • annelie
    annelie almost 2 years

    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, "");
        }
    
  • annelie
    annelie over 13 years
    The documentation I have for the SMS gateway specified 44xxxxxxxxxx as the format to send the number in, it's possible that they would accept +44, 0044, and 0xxxxxxxxx as well though. However, we want them to be able to enter any of these on the form, and even if it's fine for them to enter a non-UK number there we still need to make sure texts are only sent to UK numbers. Maybe a combination of this and the trim and replace methods is the way to go?
  • Keith
    Keith over 13 years
    If you need to accept a wide variety of formats, then a masked textbox might not be the way to go, as I can't think of a way to make it generic enough for your requirements. However the method above will be very useful for removing any non-numeric characters from the input string.