DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Simple Javascript Netmask Validation

07.28.2009
| 6807 views |
  • submit to reddit
        // netmask validation

validateNetMask = function (mask)
{
        //m[0] can be 128, 192, 224, 240, 248, 252, 254, 255
	//m[1] can be 128, 192, 224, 240, 248, 252, 254, 255 if m[0] is 255, else m[1] must be 0
	//m[2] can be 128, 192, 224, 240, 248, 252, 254, 255 if m[1] is 255, else m[2] must be 0
	//m[3] can be 128, 192, 224, 240, 248, 252, 254, 255 if m[2] is 255, else m[3] must be 0

	var flag = '';
	var correct_range = {128:1,192:1,224:1,240:1,248:1,252:1,254:1,255:1,0:1};
	var m = mask.split('.');

	for (var i = 0; i <= 3; i ++) {
		if (!(m[i] in correct_range)) {
			flag = 'Mask is not valid';
			break;
		}
	}
	
	if ((m[0] == 0) || (m[0] != 255 && m[1] != 0) || (m[1] != 255 && m[2] != 0) || (m[2] != 255 && m[3] != 0)) {
		flag = 'Mask is not valid';
	}
	
	return flag;
}