0

I'm still green with PHP and am still learning the syntax. Is it a bad idea to consolidate validation? Currently I'm validating each individual field as it is being fetched. Like so;

if ($_SERVER["REQUEST_METHOD"] == "POST") {

 if (empty($_POST["fname"])) {
    $fnameErr = "First name is required";
    ++$inc; 
    } else {
    $fnameField = test_input($_POST["fname"]);
      // check if name only contains letters and whitespace
      if (!preg_match("/^[a-zA-Z ]*$/",$fnameField)) {
        $fnameErr = "First Name: error - (Text & spaces only.)";
        ++$inc;
      }
    }

 if (empty($_POST["lname"])) {
    $lnameErr = "Last name is required";
    ++$inc;
  } else {
  $lnameField = test_input($_POST["lname"]);
        // check if name only contains letters and whitespace
      if (!preg_match("/^[a-zA-Z ]*$/",$lnameField)) {
        $lnameErr = "Last Name: error - (Text & spaces only.)";
        ++$inc;
      }
  }

   if (empty($_POST["company"])) {
    $companyErr = "Company name is required";
    ++$inc;
  } else {
  $companyField = test_input($_POST["company"]);
        // check if name only contains letters and whitespace
      if (!preg_match("/^[a-zA-Z ]*$/",$companyField)) {
        $companyErr = "Company: error - (Text & spaces only.)";
       ++$inc;
      }
  } 

Basically, is it worth consolidating these three arguments into one? If so how would I go about it?

Edit: Updated question to give full code and it's variables.

Would something like this be plausible? I know the basic concept I am after I'm just not sure the best way to get there.

PHP - With changes made as suggest by @nerdlyist.

<?php

// session start.
  session_start();

// set post data as array.
  $_SESSION['post-data'] = $_POST;

// post data array. (for note purposes to give an idea of what is in the array.)
//  $_SESSION['post-data']['fname'];
//  $_SESSION['post-data']['lname'];
//  $_SESSION['post-data']['com'];
//  $_SESSION['post-data']['ttl'];
//  $_SESSION['post-data']['ema'];
//  $_SESSION['post-data']['add1'];
//  $_SESSION['post-data']['add2'];
//  $_SESSION['post-data']['cou'];
//  $_SESSION['post-data']['tel'];
//  $_SESSION['post-data']['day'];
//  $_SESSION['post-data']['act'];
//  $_SESSION['post-data']['chk']; // << these are checkboxes.
//  $_SESSION['post-data']['rdo']; // << these are radios.

// subject & account.
  $emailSub = 'Drupa 2016 - Booking Form Actioned';
  $emailAcc = '[email protected]';

// data validation.
  if ($_SERVER["REQUEST_METHOD"] == "POST") {

  $names = array(
    "fname" => $_POST['fname'], // first name field.
    "lname" => $_POST['lname'], // last name field.
    "com" => $_POST['com'], // company name field.
    "ttl" => $_POST['ttl'], // title field.
    "ema" => $_POST['ema'], // email field.
    "add1" => $_POST['add1'], // address line 1 field.
    "add2" => $_POST['add2'], // address line 2 field.
    "cou" => $_POST['cou'], // country field.
    "tel" => $_POST['tel'] // tel field.
  );

  $errors = array();

  foreach($names as $name => $value){
      if (empty($value)) {
      $errors[] = $name."_blank";
      } else {
          // fetch data from cleaner.
             $fnameField = test_input($_POST["fname"]);
             $lnameField = test_input($_POST["lname"]);
             $comField = test_input($_POST["com"]);
             $ttlField = test_input($_POST["ttl"]);
             $couField = test_input($_POST["cou"]);
          // check if name only contains letters and whitespace
          if (!preg_match("/^[a-zA-Z ]*$/",$value)) {
              //you can only have one or the other. 
              $errors[] = $name."_clean";
          }
      }
  }

  // determining what submit or re-display.
  if(empty($errors)){
      echo "Clean form to submit";
  } else {
      echo "Rebuild the form and parse errors: ";
      print_r($errors);
  }
}

// for cleaning the data.
  function test_input($data) {

  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);

  return $data;
  }

  // checkbox array.
  $selectedProjects  = 'None';
  if(isset($_POST['chk']) && is_array($_POST['chk']) && count($_POST['chk']) > 0){
      $selectedProjects = implode(', ', $_POST['chk']);
  }

  // radio array.
  $selectedTime  = 'Afternoon';
  if(isset($_POST['rdo']) && is_array($_POST['rdo']) && count($_POST['rdo']) > 0){
      $selectedTime = implode(', ', $_POST['rdo']);
  }

  // mail body.
  $body = <<<EOD
<h3>Booking Request / $date</h3>
<hr><br>
Last Name: $lnameField <br>
First Name: $fnameField <br>
Company: $companyField <br>
Title: $titleField <br>
Email: $emailField <br>
Acitivity: $actField <br>
<br>
<h3>Contact Info</h3>
<hr><br>
Add Line 1: $add1Field <br>
Add Line 2: $add2Field <br>
Country: $countryField <br>
Telephone: $telField <br>
<br>
Requested Booking day: $daySelect <br>
Requested Booking Time: $selectedTime <br>
<br>
Interested in: $selectedProjects <br>
submitted: <b>$date</b> at <b>$time</b>.
EOD;

// form submission check.
  if isset($_POST['btn-sub'])) {

    // code executed on submit 
      $headers = "MIME-Version: 1.0\n" ;
      $headers .= "Content-Type: text/html; charset=\"iso-8859-1\"\n";
      $headers .= "X-Priority: 1 (Highest)\n";
      $headers .= "X-MSMail-Priority: High\n";
      $headers .= "Importance: High\n";
      $headers = "From: $emailField\r\n";

      $success = mail($emailAcc, $emailSub, $body, $headers);

  } else {
    // code executed on first request

    // set date & time.
      $date = date ("l, F jS, Y");
      $time = date ("h:i A"); 

    // define variables and set to empty values.
      $err = "";
      $fnameField = $lnameField = $companyField = $titleField = $emailField = $add1Field = $add2Field = $countryField = $telField = $daySelect = $actSelect = $chk = $rdo= "";
  }

  // redirect & exit.
  header('Location: prox.php');
  exit();

?>
3
  • 1
    It would stick with the DRY principle to make this a function and then just pass in the name you are validating. You would need to figure out the error message though but that should be trivial. Commented Apr 25, 2016 at 15:51
  • Do you mean like passing data into an array and passing the argument the array instead of a single target? Commented Apr 25, 2016 at 15:53
  • Would be highly recommended use POO to not repeat code like this case. Commented Apr 25, 2016 at 16:38

1 Answer 1

1

Here is something to get you started. It will add an error to errors. Not sure how you are building the form but loop the errors and if the error is _blank the field is required if it is _clean there are characters you do not like.

$names = array(
    "fname" => $_POST['fname'],
    "lname" => $_POST['lname'],
    "company" => $_POST['company']
);

$errors = array();
$inc = 0; //Not sure what this was for.
foreach($names as $name => $value){
    if (empty($value)) {
    $errors[] = $name."_blank";
    ++$inc;
    } else {
        //Not sure what this does
        //$fnameField = test_input($_POST["fname"]);
        // check if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z ]*$/",$value)) {
            //you can only have one or the other. 
            $errors[] = $name."_clean";
            ++$inc;
        }
    }
}

//This is where you can determine to submit or re-display.
if(empty($errors)){
    echo "Clean form to submit";
} else {
    echo "Rebuild the form and parse errors: ";
    print_r($errors);
}
Sign up to request clarification or add additional context in comments.

1 Comment

I have updated your question to help you understand what ++$inc and test_input() were for. Additionally, please see the updated question for full code overview and an attempt at implementing your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.