9

Possible Duplicate:
What is a regular expression for a MAC Address?

I would like to validate a string to ensure that it is a valid MAC Address.

Any ideas in Jquery or Javascript?

I have the following:

var mystring= '004F78935612'  - This type of MAC Address
var rege = /([0-9a-fA-F][0-9a-fA-F]){5}([0-9a-fA-F][0-9a-fA-F])/;
alert(rege.test(mystring));

But its not all that accurate.

Ie. My tissue box is a valid MAC Address?!?

Thanks!

Community
  • 1
  • 1
Pinch
  • 4,009
  • 8
  • 40
  • 60

1 Answers1

20

Taking the regular expression from this question, you would implement it like so:

var mystring= 'Hello';

var regex = /^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$/;

alert(regex.test(mystring));

http://jsfiddle.net/s2WDq/

This regular expression searches for the beginning of the string ^, then TWO hexidecimal digits [0-9A-F]{2}, then a colon or dash [:-], five times over (...){5}, then a final group of TWO hexidecimal digits [0-9A-F]{2}, and finally the end of the string $.

Edit: in response to your comment, Pinch, that format is not considered a valid MAC address. However, if you wanted to support it, simply add a ? in the right place:

/^([0-9A-F]{2}[:-]?){5}([0-9A-F]{2})$/
// question mark  ^ allows the colon or dash to be optional
Community
  • 1
  • 1
jbabey
  • 45,965
  • 12
  • 71
  • 94
  • I appreciate your work but a MAC Address in my case looks like 004F78935612 – Pinch Aug 17 '12 at 18:04
  • Modified pattern for your input could be `/^([0-9A-F]{2}){6}$/`, but that's not valid [notation](https://en.wikipedia.org/wiki/MAC_address). – Bryan Aug 17 '12 at 18:24
  • 1
    @Pinch see my edit. keep in mind that, according to the official specs, that is NOT a valid MAC address. – jbabey Aug 17 '12 at 18:41