Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
184
rated 0 times [  190] [ 6]  / answers: 1 / hits: 22063  / 12 Years ago, fri, august 17, 2012, 12:00:00

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!


More From » jquery

 Answers
79

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

[#83570] Thursday, August 16, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dillionsalvadorg

Total Points: 288
Total Questions: 103
Total Answers: 75

Location: South Korea
Member since Sat, Oct 2, 2021
3 Years ago
dillionsalvadorg questions
;