Manu
Manu

Reputation: 69

mac-address-validation in javascripts (00:00:00:00:00:00)

Can anyone send javascript code to validate the network mac address (eg. 02:41:6d:22:12:f1) It accepts value from 00:00:00:00:00:00 to ff:ff:ff:ff:ff:ff. On keypress event of textbox, I need to allow characters 0-9, a-f and : (colon). What I have so far is

macPattern = /^([0-9a-fA-F]{2}[:-]){5}[0-9a-fA-F]{2}$/i;

With this I am able throw exception for ff:ff:ff:ff:ff:ff but I also need to throw an exception for 00:00:00:00:00:00. My pattern is not throwing an exception.

Could you please give me a pattern through which I should able to throw an exception for both ff:ff:ff:ff:ff:ff and 00:00:00:00:00:00.

Upvotes: 2

Views: 6143

Answers (5)

Dark Burrow
Dark Burrow

Reputation: 41

I think that while the other answers are all valid, they missed the keypress aspect of the OP's question. While that might not be important in this instance, I believe that the UX can be improved.

I would suggest;

-validating length =12
-accepting {0-9,a-f,A-F},
-alert {g-z,G-Z)   (invalid character)
-ignore all others  (including Tab, cr, lf, crlf)
-confirm exit after the 12th character
-display 3 forms; raw, couplet, quad 

I have not yet had a chance to code but will submit and amend on completion

Upvotes: 0

Sagar Vaghela
Sagar Vaghela

Reputation: 1263

var MACAddress = document.getElementById("MACAddress");
var MACRegex=new RegExp("^([0-9a-fA-F][0-9a-fA-F]:){5}([0-9a-fA-F][0-9a-fA-F])$");
MACRegex.test(MACAddress);

Upvotes: 4

Prasanth
Prasanth

Reputation: 5258

Oh if we are answering about validating mac, here is mine: but this still doesn't answer the question: how to prevent characters that don't make up a mac address.

function isValidMac(mac) {
  var a = mac.split(':');
  if (a.length !== 6) {
    return false;
  }
  for (var i=0; i<6; i++) {
    var s = "0x"+a[i];
    if (s>>0 === 0 || s.length != 4) {
      return false;
    }
  }
  return true;
}

Upvotes: 0

Paul S.
Paul S.

Reputation: 66304

var re = /^(?!(?:ff:ff:ff:ff:ff:ff|00:00:00:00:00:00))(?:[\da-f]{2}:){5}[\da-f]{2}$/i;
//               ^------------blacklist------------^  ^----------pattern---------^
re.test('ff:ff:ff:ff:ff:ff'); // false
re.test('ff:ff:ff:ff:ff:fe'); // true
re.test('00:00:00:00:00:00'); // false
re.test('00:00:00:00:00:01'); // true
// and of course
re.test('00:00:00:00:01'); // false
re.test('00:00:00:00:00:0g') // false

Upvotes: 1

Robert Skarżycki
Robert Skarżycki

Reputation: 373

My answer is:

^([0-9a-fA-F]{2}[:-]){5}[0-9a-fA-F][1-9a-eA-E]$

Upvotes: -1

Related Questions