PHP 5 フォーム - E-mailとURLの検証

❮ 前章へ 次章へ ❯

この章では、名前、メールアドレス、およびURLの検証方法を説明します。


PHP - 名前の検証

下のコードは、name フィールドに文字と空白のみが含まれているかどうかを確認する簡単な方法を示しています。 name フィールドの値が正しくない場合は、エラーメッセージを格納します:

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

preg_match() 関数は、文字列内でパターンを検索し、パターンが存在する場合はtrueを返し、そうでない場合はfalseを返します。


PHP - メールアドレスの検証

メールアドレスが正しいかどうかをチェックする最も簡単で安全な方法は、PHPのfilter_var()関数を使用することです。

次のコードは、電子メールアドレスの形式が正しくない場合は、エラーメッセージを格納します:

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

PHP - URLの検証

次のコードは、URLアドレスの構文が正しいかどうかを確認する方法です (この正規表現ではURL内のダッシュを認めています)。 URLアドレスの構文が正しくなければ、エラーメッセージを格納します:

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

PHP - 名前、メールアドレス、URLの検証

スクリプトは次のようになります:

<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["name"])) {
    $nameErr = "Name is required";
  } else {
    $name = test_input($_POST["name"]);
    // check if name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
      $nameErr = "Only letters and white space allowed";
    }
  }

  if (empty($_POST["email"])) {
    $emailErr = "Email is required";
  } else {
    $email = test_input($_POST["email"]);
    // check if e-mail address is well-formed
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $emailErr = "Invalid email format";
    }
  }

  if (empty($_POST["website"])) {
    $website = "";
  } else {
    $website = test_input($_POST["website"]);
    // check if URL address syntax is valid (this regular expression also allows dashes in the URL)
    if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
      $websiteErr = "Invalid URL";
    }
  }

  if (empty($_POST["comment"])) {
    $comment = "";
  } else {
    $comment = test_input($_POST["comment"]);
  }

  if (empty($_POST["gender"])) {
    $genderErr = "Gender is required";
  } else {
    $gender = test_input($_POST["gender"]);
  }
}
?>
例の実行 »

次のステップでは、ユーザがフォームを送信するときに、フォームのすべての入力フィールドを空にしないようにする方法を示します。


❮ 前章へ 次章へ ❯