Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

Validate IP Address format

Ankita9793
Tera Contributor

Hi,

Can someone please help me with IP address validation Regex, maximum length allowed is 30, should not accept special characters including( "/" and "-" ). Should allow '" , " to enter multiple IPs.

Valid IP address formats example 

Single IP --> 10.1.1.10
Multiple IPs --> 10.0.0.10,10.0.0.11,10.0.0.12

 
6 REPLIES 6

Harish Bainsla
Kilo Patron
Kilo Patron

Hi try below code

(function executeRule(current, previous /*null when async*/) {
var ipAddresses = current.ip_addresses;

var ipRegex = /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(,\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})*)$/;

if (ipAddresses && ipAddresses.length <= 30 && ipRegex.test(ipAddresses)) {
gs.info('IP addresses are valid.');
} else {
gs.info('Invalid IP addresses format or length.');

}
})(current, previous);

Hi Harish

Thanks for responding!!

But it is not working as expected, I am trying to achieve it through client script but my client script does not allow ',' in case of multiple IP addresses

Valid IP address formats are as below... 
Single IP --> 10.1.1.10
Multiple IPs --> 10.0.0.10,10.0.0.11,10.0.0.12

 

 

function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue == '') {
        return;
    }
    var ipAddresses = g_form.getValue('enter_ip_addresses')
    var ipRegex = /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/;
    if (!ipRegex.test(ipAddresses)) {
        g_form.clearValue('enter_ip_addresses');
        g_form.triggerErrorChangeFieldSet('No spaces or special characters are allowed', 'enter_ip_addresses');
    }
    if (newValue.length > 30) {
        g_form.clearValue('enter_ip_addresses');
        g_form.showFieldMsg('enter_ip_addresses', 'Allowed maximum length is 30 characters', 'error');
    }
}