Validate IP address with JS & regex

16 January, 2020 - Reading time: ~1 minute

This is just a simple JavaScript function with some regex used to validate an IP Address format. I've used this on ServiceNow instances and before that as a PowerShell function on various Microsoft environments.

Find the JavaScript function below with a couple of examples.

function isIPValid(ip) {
    var regexIP = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/
    var testRegex = ip.match(regexIP) >= 0;
    // Returns true if it's a incorrect format
    if (testRegex) {
        return true;
    // Returns false if it's a correct format
    } else if (!testRegex) {
        return false;

Example of usage (wrong ip format)


Example of usage (correct ip format)