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
private static final String MAC_PATTERN = "^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$";
private boolean validateMAC(final String mac){
Pattern pattern = Pattern.compile(MAC_PATTERN);
Matcher matcher = pattern.matcher(mac);
return matcher.matches();
}
#Just works Perfect
#validate the MAC addr
#!/usr/bin/python
import re
mac = "01-3e-4f-ee-23-af"
result = re.match(r"([0-9a-fA-F]{2}[-:]){5}[0-9a-fA-F]{2}$",mac)
if result:
print ("Correct MAC")
else:
print ("Incorrect MAC")
If you want to ensure that there is either '-' or ':' throughout but not both, you can use following in Python:
import re
def is_valid_macaddr802(value):
allowed = re.compile(r"""
(
^([0-9A-F]{2}[-]){5}([0-9A-F]{2})$
|^([0-9A-F]{2}[:]){5}([0-9A-F]{2})$
)
""",
re.VERBOSE|re.IGNORECASE)
if allowed.match(value) is None:
return False
else:
return True
Dash-separated MAC addresses can also contain a '01-' prefix, which specifies it is an Ethernet MAC address (not token ring, for example ... who uses token ring?).
Here's something that is somewhat complete and easy to read in a logical step-through way:
def IsMac(S):
digits = S.split(':')
if len(digits) == 1:
digits = S.split('-')
if len(digits) == 7:
if digits[0] != '01':
return False
digits.pop(0)
if len(digits) != 6:
return False
for digit in digits:
if len(digit) != 2:
return False
try:
int(digit, 16)
except ValueError:
return False
return True
for test in ('01-07-09-07-b4-ff-a7', # True
'07:09:07:b4:ff:a7', # True
'07-09-07-b4-GG-a7', # False
'7-9-7-b4-F-a7', # False
'7-9-7-b4-0xF-a7'): # False
print test, IsMac(test)
This Regex validates the following MAC format
"Ae:Bd:00:00:00:00"
"00-00-00-00-00-00"
"aaaa.bbbb.cccc"
private static final String MAC_PATTERN = "(([0-9A-Fa-f]{2}[-:.]){5}[0-9A-Fa-f]{2})|(([0-9A-Fa-f]{4}\\.){2}[0-9A-Fa-f]{4})";
public class MacRegExp {
private static final String MAC_PATTERN = "(([0-9A-Fa-f]{2}[-:.]){5}[0-9A-Fa-f]{2})|(([0-9A-Fa-f]{4}\\.){2}[0-9A-Fa-f]{4})";
static boolean validateMAC(final String mac){
Pattern pattern = Pattern.compile(MAC_PATTERN);
Matcher matcher = pattern.matcher(mac);
return matcher.matches();
}
}
Hope this helps