Home » JavaScript Examples » Validating MAC Addresses Using Regular Expressions – Javascript

Validating MAC Addresses Using Regular Expressions – Javascript

Validating a MAC address using JavaScript can be a useful task, especially in scenarios where you need to ensure that users input the correct format for MAC addresses. MAC (Media Access Control) addresses are unique identifiers assigned to network interfaces, and they follow a specific format. Here’s a guide on how to validate MAC addresses using JavaScript with a complete HTML example.




About MAC Address


MAC addresses typically follow the format XX:XX:XX:XX:XX:XX or XXXX.XXXX.XXXX, where each X represents a hexadecimal digit (0-9, A-F). A valid MAC address must meet the following criteria:

  1. Length: A MAC address is 48 bits (6 bytes) long. It is usually represented as 12 hexadecimal characters, grouped in pairs separated by colons or hyphens (e.g., EA:7D:13:21:A5:44).
  2. Formatting: It can be represented in two common formats:
    • Six pairs of hexadecimal digits separated by hyphens or colons (e.g., 7a:84:ac:92:d9:15).
    • Three groups of four hexadecimal digits separated by dots (e.g., 01A2.3BCD.4E5F).

These conditions ensure a standardized way to represent MAC addresses, making them easily readable and consistent across different devices and systems.



Regex Code Snippet to Validate Mac Address


1) The regex code given below will validate 6 pairs of hexadecimal digits separated by hyphens or colons:
var pattern = /^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/


2) This regex pattern will validate both, ‘6 pairs of 2 hexadecimal digits’ and as well as ‘3 groups of 4 hexadecimal digits’, separated by hyphens or colons:
var pattern = /^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})|([0-9a-fA-F]{4}.[0-9a-fA-F]{4}.[0-9a-fA-F]{4})$/


code snippet:
function isValidMacAddress(macAddress) {
    // Regular expression for validating MAC addresses
    const macRegex = /^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})|([0-9a-fA-F]{4}.[0-9a-fA-F]{4}.[0-9a-fA-F]{4})$/;

    return macRegex.test(macAddress);
}

In this function:

  • ^: Asserts the start of the string.
  • ([0-9A-Fa-f]{2}[:-]){5}: This part matches the first five groups of two hexadecimal digits separated by either a colon : or a hyphen .
    • ([0-9A-Fa-f]{2}[:-]): This part captures a group of two hexadecimal digits followed by either a colon or a hyphen.
    • {5}: Specifies that the preceding group should occur exactly 5 times.
  • ([0-9A-Fa-f]{2}): Matches the last group of two hexadecimal digits.
  • |: Acts as an OR operator, allowing the regex to match either the MAC address format or the custom format.
  • ([0-9a-fA-F]{4}\.[0-9a-fA-F]{4}\.[0-9a-fA-F]{4}): This part matches a custom format where three groups of four hexadecimal digits are separated by dots ..
    • ([0-9a-fA-F]{4}\.[0-9a-fA-F]{4}\.[0-9a-fA-F]{4}): This part captures three groups of four hexadecimal digits separated by dots.
  • $: Asserts the end of the string.

The function returns true if the MAC address is valid and false otherwise.



Validating MAC Addresses Using JavaScript – Example


Let’s create a simple HTML example that utilizes the JavaScript function for MAC address validation. Here is the full HTML code;

.html file:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MAC Address Validation</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
            margin: 20px;
        }

        #macInput {
            padding: 8px;
            font-size: 16px;
        }

        #result {
            margin-top: 10px;
            color: green;
            font-weight:bold;
        }

        #error {
            margin-top: 10px;
            color: red;
        }
    </style>
</head>
<body>

    <h2>MAC Address Validation</h2>

    <label for="macInput">Enter MAC Address:</label>
    <input type="text" id="macInput" placeholder="e.g., 00:1A:2B:3C:4D:5E">

    <button onclick="validateMAC()">Validate</button>

    <div id="result"></div>
    <div id="error"></div>

    <script>
        function validateMAC() {
            var macInput = document.getElementById("macInput").value;
            var macRegex = /^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})|([0-9a-fA-F]{4}.[0-9a-fA-F]{4}.[0-9a-fA-F]{4})$/;

            if (macRegex.test(macInput)) {
                document.getElementById("result").innerText = "Valid MAC Address!";
                document.getElementById("error").innerText = "";
            } else {
                document.getElementById("result").innerText = "";
                document.getElementById("error").innerText = "Invalid MAC Address. Please enter a valid MAC address.";
            }
        }
    </script>

</body>
</html>

In this example:

  • We have an input field for the user to enter a MAC address.
  • There’s a “Validate” button that triggers the validateMac() function when clicked.
  • The result of the validation is displayed below the button.

Feel free to copy and paste this HTML code into an HTML file and open it in your web browser to see the MAC address validation in action.

Enter different MAC addresses to observe how the validation result changes.

example – input & output:

Test Case 1:
7a-84-ac-92-d9-15// Valid

Test Case 2:
09:df:b7:b5:42:44// Valid

Test Case 3:
01A2.3BCD.4E5F// Valid


Test Case 4:
GHIJ.KLMN.OPQR// Invalid

Test Case 5:
98-76-54-AH–32-21// Invalid



Screenshots


Here are the test results of valid & invalid MAC addresses.

1) valid mac address with colon separated:
mac address validation colon separated javascript


2) valid mac address with hypen separated:
mac address validation hypen separated javascript


3) valid mac address with dot separated(3 pairs of four hexadecimal digits):
mac address validation dots separated javascript


4) invalid mac address with hypen separated:
invalid mac address validation hypen separated javascript


4) invalid mac address with dot separated & four hexadecimal digits:
invalid mac address validation dots separated javascript

Leave a Reply

Your email address will not be published. Required fields are marked *