Open In App

How to check validation of IP Address in jQuery ?

In this article, we will find how to validate the IP Address using jQuery.

IP Address: Every computer connected to the Internet is identifiable by a unique string, which is known as its Internet Protocol (IP) address. It consists of four numbers (each between 0 and 255) separated by dots. The format of an IP address can be written as four decimal numbers separated by dots, each number can be written from 0 to 255. An example of valid IP address is as follows.



We can check whether the IP Address is valid or not using regex (regular expression) easily. Let us take an example to understand how it works. Now let us first discuss how regex can be used to validate IP addresses. The regular expression that would be used to verify IP address specifically ip4 address is as below.

^(([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])$



Example:




<!DOCTYPE html>
<html lang="en">
  <head>
    <link
      rel="stylesheet"
      href=
    <script src=
    </script>
    <script src=
    </script>
  </head>
  <body style="text-align: center">
    <h2>Jquery IP Address Checker</h2>
    <div>
      <div class="form-group row">
        <label for="inputPassword"
               class="col-sm-2 col-form-label">
          Enter IP Address:
        </label>
        <div class="col-sm-8">
          <input
            type="text"
            class="form-control"
            id="ip"
            name="ip"
            placeholder="IP Address"
          />
        </div>
      </div>
      <button type="submit" id="submit" 
              class="btn btn-primary">
        Submit
      </button>
      <p style="color: green" id="demo"></p>
  
    </div>
    <script>
      $(document).ready(function () {
        $("#submit").click(function (value) {
          // Using Regex expression for validating IPv4
          var ipaddress =
            /^(([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])$/;
          var content = $("#ip").val();
  
          if (ipaddress.test(content)) {
            $("#demo").html("Ipaddress is Valid");
          } else {
            $("#demo").html("Ipaddress is invalid");
          }
        });
      });
    </script>
  </body>
</html>

Output: The following result is shown on entering a valid and invalid IP Address.

              

IP address validation output

 


Article Tags :