Tom Tom - 2 months ago 23
jQuery Question

Validate MAC Address onkeyup

I'm trying to validate a form field for MAC Addresses.

I've got this which works.

$('body').on('keyup', '#macAddess', function(e){
var e = $(this).val();
var r = /([a-f0-9]{2})([a-f0-9]{2})/i,
str = e.replace(/[^a-f0-9]/ig, "");
while (r.test(str)) {
str = str.replace(r, '$1' + ':' + '$2');
}
e = str.slice(0, 17);
$(this).val(e)
});


As the user is typing it's formatting the MAC Address, adding
:
after every pair of characters. It will only allow a-f and 0-9 so no invalid characters are being added.

I'd like to expand on it a little.. As the user is entering the MAC address I want a class adding to input showing it is wrong, until a fully formed MAC address is entered.

eg:

if (MAC is invalid) $('#' + id).addClass('badMac')


So if the user is entering a value the class will be added and only removed when a fully formed and valid mac is entered.

I'd like to keep in all with in the
on('keyup')
function.

How do I test if it is invalid and then set the class ?

Answer

You can test it with a regular expression that checks if the MAC address is valid:

var regexp = /^(([A-Fa-f0-9]{2}[:]){5}[A-Fa-f0-9]{2}[,]?)+$/i;
var mac_address = $(this).val();
if(regexp.test(mac_address)) {
    //valid!
} else {
    //invalid!
}

Note that if you write this on keyup event, you'll obtain the invalid statement till the user writes a whole valid MAC address.

Edit

Snippet working:

var regexp = /^(([A-Fa-f0-9]{2}[:]){5}[A-Fa-f0-9]{2}[,]?)+$/i;
var mac_address = "fa:09:91:d5:e4:5a";
if(regexp.test(mac_address)) {
    console.log("Valid: "+ mac_address);
} else {
    console.log("Invalid: "+ mac_address);
}

So try this code:

$('body').on('keyup', '#macAddess', function(e){
    var e = $(this).val();
    var r = /([a-f0-9]{2})([a-f0-9]{2})/i,
    str = e.replace(/[^a-f0-9]/ig, "");
    while (r.test(str)) {
        str = str.replace(r, '$1' + ':' + '$2');
    }
    e = str.slice(0, 17);
    $(this).val(e);

    var regexp = /^(([A-Fa-f0-9]{2}[:]){5}[A-Fa-f0-9]{2}[,]?)+$/i;
    var mac_address = $(this).val();
    if(regexp.test(mac_address)) {
        //valid!
    } else {
        //invalid!
    }

});
Comments