Mych Mych - 2 years ago 177
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...

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

Answer Source

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


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download