What\'s the best way to validate that an MAC address entered by the user?
The format is HH:HH:HH:HH:HH:HH
, where each H
is a hexadecimal ch
I hate programs that force the user to think a like a computer.
Make it more friendly by accepting any valid format.
Strip the separator, whatever it is, then get the hex value that's left. That way if a user enters dashes or spaces it also works.
import string
allchars = "".join(chr(a) for a in range(256))
delchars = set(allchars) - set(string.hexdigits)
def checkMAC(s):
mac = s.translate("".join(allchars),"".join(delchars))
if len(mac) != 12:
raise ValueError, "Ethernet MACs are always 12 hex characters, you entered %s" % mac
return mac.upper()
checkMAC("AA:BB:CC:DD:EE:FF")
checkMAC("00-11-22-33-44-66")
checkMAC("1 2 3 4 5 6 7 8 9 a b c")
checkMAC("This is not a mac")