Samuel
Samuel

Reputation: 109

PHP - Form validation of fields and messages in PHP

I would like to validate the information before its send it to me. For instance that an email address has an @ on it.

I have the following code to introduce: Name, LastName and email. I validated it that they are not empty, but:

  1. How do I send a message to the user to let them know that they need to fill it up? I tried: if ($nameErr == ''){echo "Need to introduce a name"}

but it doens't work

  1. How do I make validation of type: making sure that email address has an @ or that a telephone is numeric and has 9 digits?

Thank you so much

<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>

<?php
// define variables and set to empty values
$nameErr = $emailErr = $surnameErr = "";
$name = $email = $surname = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
   if (empty($_POST["name"])) {
     $nameErr = "Name is required";
   } else {
     $name = test_input($_POST["name"]);
   }

   if (empty($_POST["email"])) {
 $emailErr = "Email is required";
   } else {
 $email = test_input($_POST["email"]);
   }

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

function test_input($data) {
   $data = trim($data);
   $data = stripslashes($data);
   $data = htmlspecialchars($data);
   return $data;
}
?>

<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo     htmlspecialchars($_SERVER["PHP_SELF"]);?>">
   Name: <input type="text" name="name">
   <span class="error">* <?php echo $nameErr;?></span>
   <br><br>
   Last Name: <input type="text" name="surname">
   <span class="error">*<?php echo $surnameErr;?></span>
   <br><br>
   E-mail: <input type="text" name="email">
   <span class="error">* <?php echo $emailErr;?></span>
   <br><br>
   <input type="submit" name="submit" value="Submit">
</form>


</body>
</html>

Upvotes: 0

Views: 50

Answers (1)

you don't actually need to code all validation yourself. It is more convenient if you use a library like http://respect.github.io/Validation/ this.

Upvotes: -1

Related Questions