Search code examples
regexpcremac-address

Mac Address RegEx to filter out Bad Macs


I have a 3rd party app that has a MAC address field that I can only apply a RegEx to for data validation. I have a RegEx that works to validate length, hex, and dashes/colons. My stumbling block is trying to prevent an entry of all the same character, all 0's, all 1's etc.

This is what I have so far:

/^(?:[A-Fa-f0-9]{2}([-:]{0,1}))(?:[A-Fa-f0-9]{2}\1){4}[A-Fa-f0-9]{2}$/

Solution

  • In PCRE you can use a negative lookahead to disallow some specific patterns.

    /^(?!(.)\1(?:[-:]?\1\1)+$)[A-Fa-f0-9]{2}([-:]?)(?:[A-Fa-f0-9]{2}\2){4}[A-Fa-f0-9]{2}$/
    

    Notice that I also refactored your regex slightly.