Gunjan Kiratkar
Kilo Patron
Kilo Patron

Hello Community Members,

 

Learning from community and giving back to it is my favourite part of day to day activity. As a result I have created blog regarding how we can effectively use REGEX for IP address validation.

I tried to add multiple validations using the REGEX for IP address which can efficiently print valid and invalid IP addresses.

 

Script :-

// Define the list of IP addresses to be validated or pass the Dynamic array of IP address 
var ipList = ["192.168.1.1",
    "192.168.1.2",
    "192.168.a.2",
    "000.173.1.4",
    "192.168.1.3",
    "63.33.733.234",
    "192.168.1.4",
    "192.168.1."
];

// Regular expression for validating 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])$/;

// Iterate through the list of IP addresses and validate each one
for (var i = 0; i < ipList.length; i++) {
    var ip = ipList[i];
    if (ipRegEx.test(ip)) {
        gs.info("Valid IP address: " + ip);
    } else {
        gs.warn("Invalid IP address: " + ip);
    }
}

 

I have written the above script in background script section of ServiceNow. You can either pass the array of IP address to validate which can be dynamic based on any field or you can pass the static value as I shown in the script.

 

Output :-

GunjanKiratkar_0-1672321839582.png

 

Feel free to add more validations in above code so that everyone can use it effectively.

 

Value added in your knowledge ??? Then please mark it as helpful, bookmark it for future use and also share it with your ServiceNow squad.