Friday, May 2, 2014

Form validation using PHP

This article going to explain how to validate form elements using PHP.
No need external library files or javascript to validate form.

Let's have a look.



Sample Form

<form method="post" action="#">
      Name:
      <input type="text" name="name"/>
      <span style="color:#FF3300"><?php echo $error;?></span> <br>
      Email:
      <input type="text" name="email"/>
      <span style="color:#FF3300"><?php echo $erro;?></span> <br>
      Contact:
      <input type="text" name="contact"/>
      <span style="color:#FF3300"><?php echo $err;?></span> <br>
      <input type="submit" name="submit" value="Submit"/>
    </form>

PHP Validation

      <?php
     //Declare variables value as empty
$name=$email=$contact="";
$error = $erro = $err = "";
if(isset($_POST['submit']))
{
    if(empty($_POST["name"])) {
    $error= "Enter your name";
    echo "<br>";
    }
    if (empty($_POST["email"])) {
     $erro="Email is required";echo "<br>";
   } else {
     $email = $_POST["email"];
     // check if e-mail is valid
     if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) {
       $erro="Invalid email format"; echo "<br>";
     }
   }
    if(empty($_POST["contact"])) {
        $err="Enter your contact number";
    }  
}
?>
Please share your comments and feedback.Thanks.

No comments:

Post a Comment