Mych Mych - 7 months ago 50
Javascript Question

regex for MAC address

I have the following that I'm using to check for a valid MAC address

function isMacValid(mac) {
var regexMac = /^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$/i
return regexMac.test(mac);
}


This works for MAC addresses that match the standard of 6 hex values separated by either a hyphen or colon...
1a:2b:3c:4d:5e:6f
or
e7-f8-90-0a-1b


I now need to account for another non-standard notation of just 6 sets of hex with no separators... so
1a2b3c4d5e6f
would be acceptable. How do I now make the : or - optional?

Answer

You can use [:-]? instead of [:-].

The only problem is that 1a:2b:3c:4d:5e6f and 1a-2b:3c:4d:5e:6f will pass the check. So to avoid that I suggest you to change :

var regexMac = /^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$/i

with

var regexMac = /^((([0-9A-F]{2}:){5})|(([0-9A-F]{2}-){5})|([0-9A-F]{10}))([0-9A-F]{2})$/i

It's less beautifull but works