Validate IP Address PHP And Javascript Examples

Overview

Below is a similar post to my other post on validate email addresses example except in this post we will validate an IP address instead of an email address. I have also provided simple and straight forward code snippets for Javascript and PHP. It uses a regular expression to test if the string passed to is a check the IP address is valid.

Validate IP Address

Validate IP Address

Validate IP Address PHP And Javascript Examples

The two types of IP Address Validation we will cover are:

I have included both PHP and Javascript Email Validation Examples. It works perfectly for me and hope it will save you hours of time trying to find it out for yourself. Please let me know in the comments if you have any issues.

Validate IP Address In PHP With preg_match()

<?php

/* The IP to test (this IP is valid) */
$str = "100.150.200.250";
/* use php's preg_match to execute the regular expression and store the result - which is either `0` for no match or `1` for a match */
$bValidIP = preg_match( '/^(([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])$/', $str );

?>

Validate IP Address In Javascript With test()

<script type="text/javascript">

/* The IP to test (this IP is valid) */
var str = "100.150.200.250";
/* The regular expression pattern */
var pattern = /^(([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])$/g;
/* use  javascript's test() function to execute the regular expression and then store the result - which is either true or false */
var bValidIP = pattern.test(str);

</script>

Conclusion

Not much explaining I can do. Essentially there are two methods to validate IP address. First is validate IP in PHP and the second is how to validate IP address in javascript.