hi

I am a newbie in PHP and is validating a form in PHP. I have an issue in this validation. The issue is that form validation is not working properly to the all of field.?

// And thats my connection code
  <?php
     $conn = mysqli_connect("localhost","root","","alkame");//procedural connection
    // Check connection
    if (mysqli_connect_errno())
      {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }
      // else{
      //    echo "Connection Established Sucessfully";
      // }
?>
=================================================
<?php include 'connection.php';?> <?php
      $firstnameErr = $lastnameErr = $emailErr = $passErr = $dateofbirthErr = "";
      $firstname = $lastname = $email = $pass =  $dateofbirth = "";
      function test_input($data) {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
      }
   function NewUser() 
   { 
     if ($_SERVER["REQUEST_METHOD"] == "POST") {
      if (empty($_POST["firstname"])) {
        $firstnameErr = "First Name is required";
      } else {
        $firstname = test_input($_POST["firstname"]);
        // check if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z ]*$/",$firstname)) {
          $firstnameErr = "Only letters and white space allowed"; 
        }
      }
   }
      if ($_SERVER["REQUEST_METHOD"] == "POST") {
      if (empty($_POST["lastname"])) {
        $lastnameErr = "Last Name is required";
      } else {
        $lastname = test_input($_POST["lastname"]);
        // check if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z ]*$/",$lastname)) {
          $lastnameErr = "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["pass"]){
      //    $passErr = "Please Enter Your Password";
      // }else{
      //    $pass = test_input($_POST["pass"])
      //    // check if e-mail address is well-formed
      // }
     $sql = "INSERT INTO users (firstname,lastname,email,pass,dateofbirth) VALUES ('$firstname','$lastname','$email','$pass','$dateofbirth')"; 
     global $conn;
     if (mysqli_query($conn, $sql)) {
         echo "New record created successfully";
     } else {
         echo "Error: " . $sql . "<br>" . mysqli_error($conn);
     }
     mysqli_close($conn);
    } 
    if(isset($_POST['submit']))
        { 
         NewUser(); 
         } 
?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <title>Modern AlkaMe</title> <!-- Bootstrap --> <link href="assets/css/bootstrap.min.css" rel="stylesheet"> <link href="assets/css/font-awesome.css" rel="stylesheet"> <link href="assets/css/style.css" rel="stylesheet"> <link href='assets/css/source-sans-pro.css' rel='stylesheet' type='text/css'> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body style="background-color: rgba(19,24,32,0.8);"> <!-- Registration page --> <div class="registration-panel"> <div class="description-panel"> <h3 class="title">Welcome to Catalyst</h3> <p>Answer a few questions to relating to your health, lifestyle and performance. The more expansive your profile is the more impactful Catalyst can be.</p> <h4 class="title">Quantify Your Life</h4> <p>Discover the efficacy of your supplements.</p> <p>Learn to optimize your performance.</p> <p>Track all your data in one place.</p> <footer> <a href="javascritp:void()">About</a> <span class="seperate">|</span> <a href="javascritp:void()">FAQ</a> <span class="seperate">|</span> <a href="javascritp:void()">Dashboard</a> </footer> </div> <div class="account-field-panel"> <header> <div class="logo"><span >Ma</span></div> <h3 class="title">Create Your Free Account</h3> </header> <form method="POST" action=""> <div class="form-group"> <label>Email</label> <input type="text" name="email" class="form-control" placeholder="..........@gmail.com" required autofocus> <span class="error">* <?php echo $emailErr;?></span> </div> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label>First Name</label> <input type="text" name="firstname" class="form-control"  placeholder="First Name" required> <span class="error">* <?php echo $firstnameErr;?></span> </div> </div> <div class="col-md-6"> <div class="form-group"> <label>Last Name</label> <input type="text" name="lastname" class="form-control"  placeholder="Last Name" required> <span class="error">* <?php echo $lastnameErr;?></span> </div> </div> </div> <div class="row"> <div class="col-md-6"> <div class="form-group password-control"> <label>Password</label> <input type="password" name="pass" class="form-control" placeholder="Password" required> <i class="fa fa-eye" aria-hidden="true"></i> <span class="error">* <?php echo $passErr;?></span> </div> </div> <div class="col-md-6"> <div class="form-group date-control"> <label>Date of Birth</label> <input type="text" name="dateofbirth" class="form-control" placeholder="mm/dd/yyyy" required> <i class="fa fa-calendar-o" aria-hidden="true"></i> <span class="error">* <?php echo $dateofbirthErr;?></span> </div> </div> </div> <div class="form-group"> <label>Term & Conditions</label> <div class="term-text"> <p>The Modern AlkaMe Consulation is an online evalution that provides a personalized, comprehensive recommendation for Nootropics based on your answer and is provided for informational purposes only.
               Neither this questionnaire nor other content on ModernAlkaMe.com is intended to diagnose or treat any medical condition and is not a substitute for seeking advice from a professional healthcare provider. If you are pregnant or have any medical conditions you should always seek the advice of your physician or other qualified health provider before starting any supplement regimen. These statements have not been evaluated by the food and drug administartration. This product is not intended to diagnose, treat, cure or prevent any disease. All purchase of goods or services on our website must be mady by adults 18 years of age or older and all user who register with our web site must be 18 years of age or older.</p> </div> </div> <div class="form-group"> <select class="form-control default-text"> <option>I agree</option> <option>I not agree</option> </select> </div> <button class="btn btn-info btn-block mtb-30" name="submit">Continue</button> </form> <div class="account-field-footer text-center">
            Alredy have an account? <a href="javascript:void()" class="links-white">Sign In</a> </div> </div> </div> </body> </html> 

Recommended Answers

All 3 Replies

Hi,

the regular expression used to validate first and last name can fail if there are special characters or a dot, like in Björk or Aldous L. Huxley, see:

So here you may want to use filter_input with FILTER_SANITIZE_STRING:

$fname = filter_input(INPUT_POST, 'firstname', FILTER_SANITIZE_STRING);

error has removed but when i put detail in registration form so the validation code is not working properly. see my code..?

<?php include 'connection.php';?>

<?php

      $firstnameErr = $lastnameErr = $emailErr = $passErr = $dateofbirthErr = "";
      $firstname = $lastname = $email = $pass =  $dateofbirth = "";

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

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

      if ($_SERVER["REQUEST_METHOD"] == "POST") {
      if (empty($_POST["lastname"])) {
        $lastnameErr = "Last Name is required";
      } else {
        $lastname = test_input($_POST["lastname"],FILTER_SANITIZE_STRING);
        // check if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z ]*$/",$lastname)) {
          $lastnameErr = "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["pass"])){
         $passErr = "Please Enter Your Password";
      }else{
         $pass = test_input($_POST["pass"]);
         // Password must be strong
         if(preg_match("/^.*(?=.{8,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/", $_POST["pass"]) === 0){
         $errPass = '<p class="errText">Password must be at least 8 characters and must contain at least one lower case letter, one upper case letter and one digit</p>';
         }
      }

      if (empty($_POST["dateofbirth"])){
          $dateofbirthErr = "Date Of Birth is required";
      }else{
         $dateofbirth = test_input($_POST["dateofbirth"]);
         // Date mask YYYY-MM-DD
         if(preg_match("/^[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}$/", $_POST["dateofbirth"]) === 0){
         $dateofbirthErr = '<p class="errText">Date must comply with this mask: YYYY-MM-DD</p>';
      }
   }

     $sql = "INSERT INTO users (firstname,lastname,email,pass,dateofbirth) VALUES ('$firstname','$lastname','$email','$pass','$dateofbirth')"; 

     global $conn;

     if (mysqli_query($conn, $sql)) {
         echo "New record created successfully";
     } else {
         echo "Error: " . $sql . "<br>" . mysqli_error($conn);
     }

     mysqli_close($conn);
    } 

    if(isset($_POST['submit']))
        { 
         NewUser(); 
         } 

?>

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="utf-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
   <title>Modern AlkaMe</title>

   <!-- Bootstrap -->
   <link href="assets/css/bootstrap.min.css" rel="stylesheet">
   <link href="assets/css/font-awesome.css" rel="stylesheet">
   <link href="assets/css/style.css" rel="stylesheet">
   <link href='assets/css/source-sans-pro.css' rel='stylesheet' type='text/css'>

   <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
   <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
   <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
   <![endif]-->
</head>
<body style="background-color: rgba(19,24,32,0.8);">
   <!-- Registration page --> 
   <div class="registration-panel">

      <div class="description-panel">
         <h3 class="title">Welcome to Catalyst</h3>
         <p>Answer a few questions to relating to your health, lifestyle and performance. The more expansive your profile is the more impactful Catalyst can be.</p>

         <h4 class="title">Quantify Your Life</h4>
         <p>Discover the efficacy of your supplements.</p>
         <p>Learn to optimize your performance.</p>
         <p>Track all your data in one place.</p>

         <footer>
            <a href="javascritp:void()">About</a> <span class="seperate">|</span>
            <a href="javascritp:void()">FAQ</a> <span class="seperate">|</span>
            <a href="javascritp:void()">Dashboard</a>
         </footer>
      </div>

      <div class="account-field-panel">
         <header> 
            <div class="logo"><span >Ma</span></div>
            <h3 class="title">Create Your Free Account</h3>
      </header>

         <form method="POST" action="">
            <div class="form-group">
               <label>Email</label>
               <input type="text" name="email" class="form-control" placeholder="..........@gmail.com" required autofocus>
                 <span class="error">* <?php echo $emailErr;?></span>
            </div>
            <div class="row">
               <div class="col-md-6">
                  <div class="form-group">
                     <label>First Name</label>
                     <input type="text" name="firstname" class="form-control"  placeholder="First Name" required>
                  <span class="error">* <?php echo $firstnameErr;?></span>
                  </div>
               </div>
               <div class="col-md-6">
                  <div class="form-group">
                     <label>Last Name</label>
                     <input type="text" name="lastname" class="form-control"  placeholder="Last Name" required>
                  <span class="error">* <?php echo $lastnameErr;?></span>
                  </div>
               </div>
            </div>
            <div class="row">
               <div class="col-md-6">
                  <div class="form-group password-control">
                     <label>Password</label>
                     <input type="password" name="pass" class="form-control" placeholder="Password" required>
                     <i class="fa fa-eye" aria-hidden="true"></i>
                      <span class="error">* <?php echo $passErr;?></span>
                  </div>
               </div>
               <div class="col-md-6">
                  <div class="form-group date-control">
                     <label>Date of Birth</label>
                     <input type="text" name="dateofbirth" class="form-control" placeholder="mm/dd/yyyy" required>
                     <i class="fa fa-calendar-o" aria-hidden="true"></i>
                      <span class="error">* <?php echo $dateofbirthErr;?></span>
                  </div>
               </div>
            </div>
            <div class="form-group">
               <label>Term & Conditions</label>
               <div class="term-text">
               <p>The Modern AlkaMe Consulation is an online evalution that provides a personalized, comprehensive recommendation for Nootropics based on your answer and is provided for informational purposes only.
               Neither this questionnaire nor other content on ModernAlkaMe.com is intended to diagnose or treat any medical condition and is not a substitute for seeking advice from a professional healthcare provider. If you are pregnant or have any medical conditions you should always seek the advice of your physician or other qualified health provider before starting any supplement regimen. These statements have not been evaluated by the food and drug administartration. This product is not intended to diagnose, treat, cure or prevent any disease. All purchase of goods or services on our website must be mady by adults 18 years of age or older and all user who register with our web site must be 18 years of age or older.</p>
               </div>
            </div>
            <div class="form-group">
               <select class="form-control default-text">
                  <option>I agree</option>
                  <option>I not agree</option>
               </select>
            </div>
            <button class="btn btn-info btn-block mtb-30" name="submit">Continue</button>
         </form>
         <div class="account-field-footer text-center">
            Alredy have an account? <a href="javascript:void()" class="links-white">Sign In</a> 
         </div>
      </div>

   </div>

</body>
</html>

Hi,

so the validation code is not working properly.

can you give details about what does not work properly?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.