Skip to content
Advertisement

REGEX for IP address which is incomplete

I have a form where I’m storing IP address. The form validations must have 3 conditions.

  1. Where the user has to enter the entire IP eg:(100.10.10.100)
  2. Where the user enters the first 2 parts and put a star * in the remaining fields eg: (100.10.*. *)
  3. Where the user enters the first 3 parts and put a star * in the last field eg:(100.10.10.*)

My form looks like this

<form method="post" class="get-ip" action="action.php" name="get-ip" id="get-ip">
  <label for="ip-address">Enter IP Address</label>
  <input type="text" class="ip-address" id="ip-address" name="ip-address">
  <input type="submit" class="submit-ip" name="submit-ip" value="Submit IP">
</form>

My validation looks like this

if(isset($_POST["submit-ip"])){
  $ip = $_POST["ip-address"];
  $ipCheck = '/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/';
  if(preg_match($ipCheck, $ip)){
    /*Do something*/
  }
}

This is how far I’ve been. I can validate if the IP is real or not, but I’m stuck on the 2nd and 3rd point as I don’t have any REGEX that matches those conditions.

EDIT I’ve managed to get the third REGEX which is

$thirdCondition = '/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[*]?)$/';

I’m stuck on the 2nd condition now

Advertisement

Answer

Have 3 regexex

$first_condition = '/^d{1,3}.d{1,3}.d{1,3}.d{1,3}z/';
$second_condition = '/^d{1,3}.d{1,3}.d{1,3}.[*]z/';
$third_condition = '/^d{1,3}.d{1,3}.[*].[*]z/';
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement