Ankur Bawiskar
Tera Patron
Tera Patron

Many a times you would require validation for IP Address if there is a field on the form.

  • A valid IPv4 address should be in the form of xxx.xxx.xxx.xxx, where xxx is a number from 0-255.
  • Class A IP addresses are networks belonging from 1.0.0.0 to 127.0.0.0. Class B is networks 128.0.0.0 through 191.255.0.0. Class C is 192.0.0.0 through 223.255.255.0
  • IP Address 0.0.0.0 is valid since it contains four octets, each within the range 0 through 255 inclusive. However, it's not usable as a real IP address.
  • Valid IP Address always are in between the extreme values, "0.0.0.0" and "255.255.255.255" excluding these extreme values.

For example below are few valid IPv4 Addresses:

10.10.10.10

192.168.1.1

Invalid IPv4 Addresses:

192.168.1.256

255.245.276.243

There exists already a field type IP Address; you can try using that.

Here is the onChange Script on the field:

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
	if (isLoading || newValue === '') {
		return;
	}
	
	var val = validateIP(newValue);
	
	if(val == 'reserved'){
		alert('This is a reserved IP address so cannot be used');
		g_form.clearValue('fieldName');
	}
	else if(!val){
		alert('Please enter valid IP Address');
		g_form.clearValue('fieldName');
	}
	
}
function validateIP(ip) {
	alert('inside function');
	
	if(ip == '0.0.0.0' || ip == '255.255.255.255')
		return 'reserved';
	
	//Check Format
	var ip = ip.split(".");
	
	if (ip.length != 4) {
		return false;
	}
	
	//Check Numbers
	for (var c = 0; c < 4; c++) {
		//Perform Test
		if ( ip[c] <= -1 || ip[c] > 255 ||
			isNaN(parseFloat(ip[c])) ||
		!isFinite(ip[c])  ||
		ip[c].indexOf(" ") !== -1 ) {
			
			return false;
		}
	}
	return true;
}

Kindly do not forget to like or bookmark this post if it helps you.

Kindly input your suggestions if any once you use this.

14 Comments