Mask a Phone Number Field but Only Save the Numbers using jQuery

Masking a phone number field is relatively easy by utilizing one of the many jQuery masking plug-ins. It will turn your input field from this: 5554449999 into this: (555) 444-9999 which looks much nicer but at the same time that becomes the text that will be sent when you post back the form to the server.

Of course, by simply using a mask, we gain several things such as normalized input and a bit of client-side validation since it limits the input to just numbers in this case.

So why would we want to only save the numbers? Well, by normalizing your input to only numbers, it makes it a lot easier to query for phone numbers in your database. If you don’t have such a mask and only utilize validation on input that confirms that the numbers entered do equal a phone number, then you can end up with a database filled with entries such as these:

SELECT     TOP 5 *
FROM       CustomerPhoneNumbers

(555) 444-9999
555-444-9999
5554449999
(555)4449999
555 444 9999

How are you supposed to query that mess?

So by masking your input, you will provide a more pleasant experience for the user and by only saving the numbers, you will normalize your input of phone numbers and can always be assured that numbers in your database will conform to a specific standard.

To accomplish this, we will use the jQuery library, 2 jQuery plug-ins and a custom script:

Here is the HTML:

<!-- Insert scripts here -->
<form id="form1" method="post">
    This script will normalize your phone numbers and only save the numerical digits.
    <br /> 
    Phone Number: <input id="txtPhoneNumber" name="FancyPhoneNumber" class="required phone" type="text" /> 
    <input id="btnSubmit" type="submit" value="Submit" /> 
    <input id="txtHiddenPhoneNumber" name="PhoneNumber" type="hidden" value="" /> 
</form> 

And here is the Javascript:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript" src="http://cloud.github.com/downloads/digitalBush/jquery.maskedinput/jquery.maskedinput-1.3.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.8.1/jquery.validate.min.js"></script>
<script type="text/javascript">
		$(document).ready(function() {

			//Set mask for phone number field
			$("#txtPhoneNumber").mask("(999) 999-9999");

			//Store numbers in hidden field
			$("#txtPhoneNumber").blur(function () {

				//Clear the hidden field
				$("#txtHiddenPhoneNumber").val("");

				//Create char array from phone number field
				var charArray = $(this).val().split("");

				var phoneNumber = "";

				//Iterate over each character in the char array
				//and determine if it is a number
				$.each(charArray, function(index, value) {
					if (!isNaN(value) && value != " ") {
						phoneNumber = phoneNumber + value;
					}
				});

				//Set hidden field
				$("#txtHiddenPhoneNumber").val(phoneNumber);
			});

			$("#btnSubmit").click(function () {
				//If valid, show hidden field contents so we can
				//confirm that it is indeed just saving the number
				if($("#form1").valid()) {	
					alert("Value in hidden field: " + $("#txtHiddenPhoneNumber").val());
				}
			});
		});

</script>

And here is the demo:


Of course, all of this can be done on the server side as well using many different tactics.
Using ASP.NET MVC, we could throw the example HTML above into a View and create an Action that could convert the “Fancy Phone Number” into only numerical digits.

Below is an example Action that uses two different methods to convert a string phone number to numbers only:

        [HttpGet]
        public ActionResult Demo()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Demo(string PhoneNumber, string FancyPhoneNumber)
        {
            string replaceNumber = String.Empty;
            string parseNumber = String.Empty;

            //Convert to numbers-only using .Replace()
            if (!String.IsNullOrWhiteSpace(FancyPhoneNumber))
            {
                replaceNumber = FancyPhoneNumber.Replace("(", "").Replace(")", "").Replace(" ", "").Replace("-", "");
            }

            //Convert to numbers-only using .TryParse()
            foreach (var c in FancyPhoneNumber)
            {
                int num;
                parseNumber += int.TryParse(c.ToString(), out num) ? num.ToString() : ""; 
            }

            return Content("You posted:<br/>" + 
                           "Fancy Phone Number = " + FancyPhoneNumber + 
                           "<br/>Hidden Field Phone Number = " + PhoneNumber +
                           "<br/><br/>C# .replace() method converted your Fancy Phone Number to this: " + replaceNumber + 
                           "<br/>C# TryParse() method converted your Fancy Phone Number to this: " + parseNumber);
        }

And if you were to run this, the output would be:

You posted:
Fancy Phone Number = (555) 444-9999
Hidden Field Phone Number = 5554449999

C# .replace() method converted your Fancy Phone Number to this: 5554449999
C# TryParse() method converted your Fancy Phone Number to this: 5554449999