Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery / JavaScript MAC Address Validation [duplicate]

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!

like image 567
Pinch Avatar asked Aug 17 '12 17:08

Pinch


1 Answers

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
like image 64
jbabey Avatar answered Nov 05 '22 05:11

jbabey