Format MAC Address [JavaScript]

I am currently working on a project which will allow users to register their Wi-Fi enabled, non-web browser enabled, devices on the network. These are devices like printers, Apple TV, and Xbox*. One of the data points that have to be collected from the user is the device MAC address. The project customer wants that address to be properly formatted when they see it in the support ticket.

We have several options. We can format the address either on the back-end after the form has been submitted. Or we can format it on the front end via a separate text field for each character pair, but that is too many fields to handle. A better solution is to use a single field and format the user input at the time of input or upon submit. In those cases, the former is better because the data will already be formatted when the overall form input is being validation after the user clicks the “Submit” button.

We are going to format the user input as it is being provided, thus having proper data when validated upon submit; when the request is being processed on the back-end; and in the resulting support ticket.

Out function is going to perform the following actions:
  1. Receive the user input as the form field object. I will explain below.
  2. Change all letters from the object value to upper case.
  3. If said value string is less than a complete MAC address (17 characters):
    1. Remove all non-alphanumeric characters. This is going to remove any delimiters the user might use.
    2. Append a colon (:) after every second character.
  4. Update the field value with the new string.


In step 1 we wanted to receive the field object instead of just the input because on line 20 we use the "id" property of the object to update the field with the formatted string.

Below is one way to implement the MAC address formatting script.


Note line 27! We are not going to invoke the "formatMacAddress" function when the user is pressing the backspace key.

___
* As of this writing Microsoft announced within the last week that with their upcoming Xbox One update they are going to enable support for Wi-Fi authentication via the Xbox web browser

Popular posts from this blog

Validate Email Address [JavaScript]

SNOOZ: Sound. Sleep.

Format a number as US currency [JavaScript]