isValidMACAddress
Checks if a string is a valid MAC address.
1/**
2 * Checks if a string is a valid MAC address.
3 *
4 * Accepts formats like:
5 * - "00:1A:2B:3C:4D:5E"
6 * - "00-1A-2B-3C-4D-5E"
7 * - "001A.2B3C.4D5E"
8 *
9 * @param str - The MAC address string to validate.
10 * @returns True if the string is a valid MAC address.
11 */
12export function isValidMACAddress(str: string): boolean {
13 const patterns = [
14 // 00:1A:2B:3C:4D:5E or 00-1A-2B-3C-4D-5E
15 /^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/,
16 // 001A.2B3C.4D5E
17 /^([0-9A-Fa-f]{4}\.){2}([0-9A-Fa-f]{4})$/
18 ];
19 return patterns.some(pattern => pattern.test(str));
20}
Supports Multiple Common Formats
Recognizes all widely used MAC address formats: colon-separated, hyphen-separated, and dot-separated (Cisco style).
Robust Pattern Matching
Uses precise and well-structured regular expressions to ensure format correctness, avoiding false positives.
Case-Insensitive Validation
Accepts both uppercase and lowercase hexadecimal characters, increasing flexibility for user input.
Compact and Readable Logic
The use of an array of regex patterns with
.some()
offers a concise and maintainable validation approach.
Tests | Examples
1test('isValidMACAddress - accepts colon-separated MAC', () => {
2 expect(isValidMACAddress('00:1A:2B:3C:4D:5E')).toBe(true);
3});
4
5test('isValidMACAddress - accepts hyphen-separated MAC', () => {
6 expect(isValidMACAddress('00-1A-2B-3C-4D-5E')).toBe(true);
7});
8
9test('isValidMACAddress - accepts dot-separated MAC', () => {
10 expect(isValidMACAddress('001A.2B3C.4D5E')).toBe(true);
11});
12
13test('isValidMACAddress - rejects invalid characters', () => {
14 expect(isValidMACAddress('00:1G:2B:3C:4D:5E')).toBe(false);
15});
16
17test('isValidMACAddress - rejects wrong length', () => {
18 expect(isValidMACAddress('00:1A:2B:3C:4D')).toBe(false);
19});
20
21test('isValidMACAddress - rejects malformed format', () => {
22 expect(isValidMACAddress('001A-2B3C-4D5E')).toBe(false);
23});
Common Use Cases
Device Configuration Forms
Validate user-entered MAC addresses in network tools or IoT dashboards.
Network Access Control
Ensure MAC addresses are well-formed before using them in authentication or filtering systems.
Parsing and Importing Device Lists
Sanitize bulk input of MAC addresses from CSVs or APIs before further processing.
Monitoring and Logging Systems
Validate and format MAC addresses collected from logs or SNMP traps for consistent display or storage.