Validate MAC Address with JS & regex

10 January, 2020 - Reading time: ~1 minute

This is just a simple JavaScript function with some regex used to validate an alidate a MAC Address format. I've used this on ServiceNow instances and before that as a PowerShell function on various Microsoft environments.

Find the JavaScript function below with a couple of examples.

function isMacValid(mac) {
    var regexMac = /^((([0-9A-F]{2}:){5})|(([0-9A-F]{2}-){5})|([0-9A-F]{10}))([0-9A-F]{2})$/i
    var testRegex = mac.match(regexMac) >= 0;
    // Returns true if it's a incorrect format
    if (testRegex) {
        return true;
    // Returns false if it's a correct format
    } else if (!testRegex) {
        return false;
    }
}

Example of usage (wrong mac format)

isMacValid('1a:2b:3c:4d:5e6f');

Example of usage (correct mac format)

isMacValid('1a:2b:3c:4d:5e:6f');