IPv4 Address Validator

IPv4 Address Validator

A common programming exercise is to write some code that will validate an IP address. IPv4 addresses are displayed canonically using dot-decimal notation and they consist of four decimal numbers or octets that range from zero to 255 separated by periods. For example, your IP address is

Let’s build a simple form that will validate an IPv4 address using JavaScript and Regular Expression. To do this we are going to need three files: index.html, validator.js and style.cssĀ the web page, the JavaScript and the stylesheet, respectively.

Below are the 24 lines of HTML we will need for the web page, index.html:

<!DOCTYPE html>
<html lang="en">
    <meta charset="utf-8">
    <title>JavaScript IPv4 Address Validator</title>
    <link rel="stylesheet" type="text/css" href=style.css">
<body onload='document.ipform.ipaddr.focus()'>
<div class="container">
    <h2>Enter an IP address then click 'Validate'</h2>
    <form name="ipform" action="#">
            <li><input type='text' name='ipaddr'/></li>
            <li class="submit">
                <button onclick="ValidateIPaddress(document.ipform.ipaddr)">VALIDATE</button>
<script type="text/javascript" src="validator.js"></script>

Below are the 12 lines of JavaScript we need for the validator script, validator.js:

function ValidateIPaddress(inputText) {
var ipformat = /^(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]?)$/;
if (inputText.value.match(ipformat)) {

alert("You entered a valid IPv4 address.");
return false;
} else {
alert("You entered an invalid IPv4 address.");
return false; }

To make the form look a little better, let’s use the 50 lines of CSS below in the stylesheet, style.css:

@import url('https://fonts.googleapis.com/css?family=Roboto&display=swap');

body, p, h1, h2, li, input {
font-family: 'Roboto', sans-serif;

h2 {
color: #FFF;

button:hover {
background-color: #000;
color: white;

button {
background-color: #FFF;
color: black;
font-size: 1em;
border: 2px solid;

.container {
margin: auto;
padding: 12px;
width: 40em;
background: #5882FA;
border-radius: 23px;

ul {
list-style-type: none;

input {
font-size: 20pt;

input:focus, textarea:focus {
background-color: #E0F8F1;

input submit {
font-size: 12pt;

.rq {
color: #FF0000;
font-size: 10pt;

Once you put it all together, you will end up with a form that looks like the one below:

IPv4 Address Validator

Click on the image to see the IPv4 Address Validator in action. Thanks for reading! Feel free to leave your comments, suggestions and/or feedback below.