Click to See Complete Forum and Search --> : javascript question - validate mac address


fizch
April 29th, 2003, 02:15 PM
I am trying to validate a mac address that has been keyed by a user. I am not exactly sure how to convert a character to a digit to compare to an ascii character code or how to convert the character to hexadecimal. Either would work well, but every method I have tried has failed. :mad: Below is the code that I am using as well as some scratch work.


function validateMacAddress(oFormObj) {
myMac = String(oFormObj.value);
myMac = myMac.toUpperCase();
oFormObj.value = myMac;

if (myMac.length != 12) {
alert('Length failure!');
return false;
}

for(i=0; i < 12; i++) {
myChar = myMac.charAt(i);
alert(myChar);
myDigit = Character.digit(myChar, 10);
alert(myDigit);
/*if (Character.digit(myChar, 16) > 16) {
alert ("Character Failure");
}
*/
}
}

Satishpp
April 29th, 2003, 04:10 PM
I am trying to validate a mac address that has been keyed by a user.

Are you trying to validate the mac address for a particular pattern?

I dont understand the problem or what your code is doing

Could you elaborate?

:confused:

Satish

fizch
April 29th, 2003, 04:11 PM
The code is just verifying that there are 12 characters and that all of the characters are in a hexadecimal range (0 - 15)

Satishpp
April 29th, 2003, 04:47 PM
OK, now I get it.

The cleanest and most efficient solution to this would be to use Javascript regular expressions. That way you can write a script that validates the values entered to 0-9 and A-F

I dont have an example right now, but a search on the Internet should give you hundreds of samples.

Satish

fizch
April 30th, 2003, 08:31 AM
I am not having much luck using the Regular Expression. Here is what I have tried.



reHex = new RegExp("0|1|2|3|4|5|6|7|8|9|a|b|c|d|e|f", "gi")

if (!myMac.search(reHex)) {
alert("Hex Failed");
return false;
}


I am probably using the wrong type of regular expression, but I am rather unfamiliar with the concept.

Satishpp
April 30th, 2003, 02:29 PM
This should work

var regex="";
var teststr="";
function mactest()
{
regex=/(\d|[a-f]){12}/;
teststr=document.frm1.txt1.value;
if (regex.test(teststr))
{
alert("Valid mac address");
}
else
{
alert("Not a valid mac address");
}
}

where document.frm1.txt1 is the form field where the value is entered.

Satish

fizch
April 30th, 2003, 02:48 PM
Actually, that did not work for me. However, I have changed the logic a little and done my validation with a nice long If statement.

srenon
July 1st, 2009, 11:44 AM
3 standard (IEEE 802) formats:

0a:1b:3c:4d:5e:6f
0a-1b-3c-4d-5e-6f
0a1b.3c4d.5e-6f



<script type="text/javascript">

teststr="0a:1b:3c:4d:5e:6f";

regex=/^([0-9a-f]{2}([:-]|$)){6}$|([0-9a-f]{4}([.]|$)){3}$/i;

if (regex.test(teststr)){
document.write("Valid mac address");
}
else{
document.write("Not a valid mac address");
}

</script>

srenon
July 1st, 2009, 11:48 AM
3 standard (IEEE 802) formats:

0a:1b:3c:4d:5e:6f
0a-1b-3c-4d-5e-6f
0a1b.3c4d.5e6f