PHP - Validate Name, E-mail, and URL


SUBMITTED BY: Guest

DATE: Oct. 7, 2014, 12:34 p.m.

FORMAT: Text only

SIZE: 1.6 kB

HITS: 1106

  1. <?php
  2. // define variables and set to empty values
  3. $nameErr = $emailErr = $genderErr = $websiteErr = "";
  4. $name = $email = $gender = $comment = $website = "";
  5. if ($_SERVER["REQUEST_METHOD"] == "POST") {
  6. if (empty($_POST["name"])) {
  7. $nameErr = "Name is required";
  8. } else {
  9. $name = test_input($_POST["name"]);
  10. // check if name only contains letters and whitespace
  11. if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
  12. $nameErr = "Only letters and white space allowed";
  13. }
  14. }
  15. if (empty($_POST["email"])) {
  16. $emailErr = "Email is required";
  17. } else {
  18. $email = test_input($_POST["email"]);
  19. // check if e-mail address is well-formed
  20. if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  21. $emailErr = "Invalid email format";
  22. }
  23. }
  24. if (empty($_POST["website"])) {
  25. $website = "";
  26. } else {
  27. $website = test_input($_POST["website"]);
  28. // check if URL address syntax is valid (this regular expression also allows dashes in the URL)
  29. if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
  30. $websiteErr = "Invalid URL";
  31. }
  32. }
  33. if (empty($_POST["comment"])) {
  34. $comment = "";
  35. } else {
  36. $comment = test_input($_POST["comment"]);
  37. }
  38. if (empty($_POST["gender"])) {
  39. $genderErr = "Gender is required";
  40. } else {
  41. $gender = test_input($_POST["gender"]);
  42. }
  43. }
  44. ?>

comments powered by Disqus