PHP 合并验证


PHP consolidating validation

我仍然对PHP很感兴趣,并且仍在学习语法。合并验证是一个坏主意吗?目前,我正在验证每个单独的字段,因为它正在被获取。这样;

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;
      }
  } 

基本上,是否值得将这三个论点合并为一个?如果是这样,我将如何去做?

编辑:更新了问题以提供完整的代码及其变量。

这样的事情是合理的吗?我知道我的基本概念,只是不确定到达那里的最佳方式。

PHP - 按照@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 = 'test@test.co.uk';
// 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();
?>

这里有一些东西可以帮助你开始。它会向错误添加错误。不确定您如何构建表单,但循环错误,如果错误_blank则字段是必需的,如果它_clean您不喜欢的字符。

$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);
}