javaScript IP address validation; Through this tutorial, i am going to show you how to validate an IP address in Javascript with the help of examples.
An IP address, or simply an “IP,” is a unique address that identifies a device on the Internet or a local network. It allows a system to be recognized by other systems connected via the Internet protocol. There are two primary types of IP address formats used today — IPv4 and IPv6
Following examples of IP address:
- 116.42.150.38
- 192.168.1.5
- 110.234.52.124
JavaScript IP Address Validation Tutorial
- Step 1: Create one HTML File
- Step 2: Validate an IP address in JavaScript
- Demonstration of the Regular expression (IP address)
Step 1: Create one HTML File
First of all, you need to create one HTML file and update the following html code into your file:
<!DOCTYPE html> <html> <title>JavaScript IP address Validation</title> <body onload='document.form1.ip_address.focus()'> <div class="mail"> <h2>Enter an IP address and Submit</h2> <form name="form1" action="#"> <input type='text' name='ip_address' placeholder="e.g. 192.168.1.1"/> <input type="submit" name="submit" value="Submit" onclick="ValidateIPaddress(document.form1.ip_address)"/> </form> </div> </body> </html>
Step 2: Validate an IP address in JavaScript
Next, update the below javascript code to your html file. So you can validate ip address in javascript using the following function:
<script> 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)) { document.form1.ip_address.focus(); return true; } else { alert("You have entered an invalid IP address!"); document.form1.ip_address.focus();return false; } } </script>
For better understanding, we would love to share with you regular expression patterns and uses of this pattern in javascript.
Demonstration of the Regular expression (IP address)
Regular Expression Pattern :
/^(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]?)$/
The below table demonstrates regular expression characters one by one. You can use these characters and create your own validation functions in javascript.
Character | Description |
---|---|
/ .. / | All regular expressions start and end with forward slashes. |
^ | Matches the beginning of the string or line. |
25[0-5] | Matches 250 or 251 or 252 or 253 or 254 or 255. |
| | or |
2[0-4][0-9] | Start with 2, follow a single character between 0-4 and again a single character between 0-9. |
| | or |
[01] | |
? | Matches the previous character 0 or 1 time. |
[0-9][0-9] | Matches a single character between 0-9 and again a single character between 0-9. |
? | Matches the previous character 0 or 1 time. |
\. | Matches the character “.” literally. |