Skip to content

Validate IP address with JS & regex

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

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)

isIPValid('192.168.1250');

Example of usage (correct ip format)

isIPValid('192.168.1.250');

Published inDevelopment

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

© 2020 Tech[Net] | Crafted with ♥ by Morten & rollin' on Author