HOME HTML EDITOR C JAVA PHP

PHP Form URL/E-mail Validation

After ensuring that fields are not empty, the next step is to verify that the data submitted is in the correct format. PHP provides powerful tools like filter_var() and Regular Expressions (RegEx) for this purpose.

1. Validating E-mail

The easiest and safest way to check if an e-mail address is well-formed is to use the filter_var() function with the FILTER_VALIDATE_EMAIL filter.

<?php
  $email = test_input($_POST["email"]);
  if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $emailErr = "Invalid email format";
  }
?>

2. Validating URL

To validate a website URL, we use a Regular Expression. The pattern below checks if the URL syntax is valid and allows for protocols like http, https, and ftp.

<?php
  $website = test_input($_POST["website"]);
  if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i", $website)) {
    $websiteErr = "Invalid URL";
  }
?>

3. Validating Name (Letters Only)

For a name field, you usually want to restrict input to only letters and white spaces. We use the preg_match() function to enforce this rule.

<?php
  $name = test_input($_POST["name"]);
  if (!preg_match("/^[a-zA-Z-' ]*$/", $name)) {
    $nameErr = "Only letters and white space allowed";
  }
?>

4. Why Validation Matters

Proper validation prevents "bad data" from entering your system. This includes:

Note: While filter_var() is great for emails, complex strings like URLs often require Regular Expressions to handle different protocols and domain extensions correctly.