PHP Form Validation - Validating E-mail and URL

This section shows how to validate name, email, and URL.

PHP - Validating Name

The following code demonstrates a simple method to check if the name field contains letters and spaces. If the name field is invalid, an error message is stored:

$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
  $nameErr = "Only letters and spaces allowed!"; 
}

Note:The preg_match() function retrieves the pattern of the string, and returns true if the pattern exists, otherwise returns false.

PHP - Validating E-mail

The following code demonstrates a simple method to check if the e-mail address syntax is valid. If it is invalid, an error message is stored:

$email = test_input($_POST["email"]);
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) {
  $emailErr = "Invalid email format!"; 
}

PHP - Validating URL

The following code demonstrates a method to check if the URL syntax is valid (this regular expression also allows slashes in the URL). If the URL syntax is invalid, an error message is stored:

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

PHP - Validating Name, E-mail, and URL

Now, the script looks like this:

Example

<?php
// Defining variables and setting them to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["name"])) {
    $nameErr = "Name required";
  }
    $name = test_input($_POST["name"]);
    // واریس کردن نام شامل حروف و فضاهای خالی
    if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
      $nameErr = "Only letters and white space allowed"; 
    }
  }
  if (empty($_POST["email"])) {
    $emailErr = "Email required";
  }
    $email = test_input($_POST["email"]);
    // واریس کردن آدرس ایمیل به صورت معتبر
    if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) {
      $emailErr = "Invalid email format"; 
    }
  }
  if (empty($_POST["website"])) {
    $website = "";
  }
    $website = test_input($_POST["website"]);
    // بررسی آدرس URL زبان URL معتبر است (این عبارت正则 نیز اجازه خطوط زیر خط URL را می‌دهد)
    if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%",
    =~_|]/i,$website)) {
      $websiteErr = "Invalid URL"; 
    }
  }
  if (empty($_POST["comment"])) {
    $comment = "";
  }
    $comment = test_input($_POST["comment"]);
  }
  if (empty($_POST["gender"])) {
    $genderErr = "Gender is required";
  }
    $gender = test_input($_POST["gender"]);
  }
}
?>

مثال اجرایی

در اینجا به شما توضیح خواهم داد که چگونه می‌توانید از خالی شدن تمام فیلدهای ورودی فرم بعد از ارسال فرم توسط کاربر جلوگیری کنید.