Example of PHP form validation

In this article, we'll build and validate a basic Web form using HTML and PHP, and complete the validation of the content using PHP.
A form contains: text fields, radio buttons, multiple choice select lists, checkboxes, and a submit button. PHP will be used to validate these to ensure the user has filled in all the values.
If the field is empty, the error string "cannot be empty" will be output next to the field. If all fields are filled, the filled value is displayed.
web form
insert image description here

form element

<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

PHP authentication

<?php
$errors = [];
$fields = ['name', 'address', 'email', 'howMany', 'favoriteFruit', 'brochure'];
$optionalFields = ['brochure'];
$values = [];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    foreach ($fields as $field) {
        if (empty($_POST[$field]) && !in_array($field, $optionalFields)) {
            $errors[] = $field;
        } else {
            $values[$field] = $_POST[$field];
        }
    }

$errors: Initially empty to store form fields that failed validation
$fields: Stores all field names to process
$optionalFields: Stores optional field names
$values: Initially empty, this is an associative array that will contain the provided fields and their values

After checking the submission for errors, and if there were no errors, the code prints out the user-submitted value in a fairly basic fashion:

if (empty($errors)) {
        foreach ($fields as $field) {
            if ($field === "favoriteFruit") {
                printf("%s: %s<br />", $field, var_export($_POST[$field], TRUE));
            } else {
                printf("%s: %s<br />", $field, $_POST[$field]);
            }
        };
        exit;
    }
}

show error message

<?php if (in_array('name', $errors)): ?>
  <span class="error">姓名不能为空</span>
<?php endif; ?>

insert image description here
The extension form
can also remember selections made by the user from radio buttons

<input type="radio" name="howMany"
 <?php if (isset($howMany) && $howMany == "zero") echo "checked"; ?>
 value="zero"> 0
<input type="radio" name="howMany"
 <?php if (isset($howMany) && $howMany == "one") echo "checked"; ?>
 value="one"> 一种
<input type="radio" name="howMany"
 <?php if (isset($howMany) && $howMany == "two") echo "checked"; ?>
 value="two"> 两种
<input type="radio" name="howMany"
 <?php if (isset($howMany) && $howMany == "twoplus") echo "checked"; ?>
 value="twoplus"> 两种以上

Complete PHP verification example code

<?php
$errors = [];
$fields = ['name', 'address', 'email', 'howMany', 'favoriteFruit', 'brochure'];
$optionalFields = ['brochure'];
$values = [];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  foreach ($fields as $field) {
    if (empty($_POST[$field]) && !in_array($field, $optionalFields)) {
      $errors[] = $field;
    } else {
      $values[$field] = $_POST[$field];
    }
  }

  if (empty($errors)) {
    foreach ($fields as $field) {
      if ($field === "favoriteFruit") {
        printf("%s: %s<br />", $field, var_export($_POST[$field], TRUE));
      } else {
        printf("%s: %s<br />", $field, $_POST[$field]);
      }
    }
    exit;
  }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>水果世界</title>
  <style type="text/css">
    body {
      
      
      background-color: #FAFAF9;
      color: #111827;
      padding: 15px;
    }
    h1, h2 {
      
      
      margin-bottom: 10px;
    }
    h2 {
      
      
      margin-top: 10px;
    }
    .wrapper {
      
      
      background-color: #312E81;
      color: #ffffff;
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 10px;
      width: 95%;
      padding: 15px;
      border-radius: 5px;
    }
    .wrapper div:last-child {
      
      
      grid-column: 2;
    }
    label, .field-label {
      
      
      padding-top: 10px;
      text-align: right;
    }
    input {
      
      
      padding: 10px 10px 10px 5px;
    }
    input, option {
      
      
      color: #1F2937;
      font-size: 1.1rem;
    }
    .error {
      
      
      color: #FF0000;
    }
  </style>
</head>
<body>
<h1>天宁日记</h1>
<h2>果蔬销售调查表</h2>
<p>www.axzb.com</p>
<form class="wrapper" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
  <label for="name">姓名</label>
  <div>
    <input type="text"
           name="name"
           id="name"
           value="<?php echo htmlspecialchars($values['name']);?>">

    <?php if (in_array('name', $errors)): ?>
      <span class="error">姓名不能为空</span>
    <?php endif; ?>
  </div>

  <label for="address">住址</label>
  <div>
    <input type="text"
           name="address"
           id="address"
           value="<?php echo htmlspecialchars($values['address']);?>">

    <?php if (in_array('address', $errors)): ?>
      <span class="error">住址不能为空</span>
    <?php endif; ?>
  </div>

  <label for="email">邮箱</label>
  <div>
    <input type="text"
           name="email"
           id="email"
           value="<?php echo htmlspecialchars($values['email']);?>">

    <?php if (in_array('email', $errors)): ?>
      <span class="error">邮箱不能为空</span>
    <?php endif; ?>
  </div>

  <div class="field-label">每日消耗的果蔬数量</div>
  <div>
    <label>
      <input type="radio"
             name="howMany"
             <?php if (isset($values['howMany']) && $values['howMany'] == "zero") echo "checked"; ?>
             value="zero">
      0
    </label>
    <label>
      <input type="radio"
             name="howMany"
             <?php if (isset($values['howMany']) && $values['howMany'] == "one") echo "checked"; ?>
             value="one">
      一种
    </label>
    <label>
      <input type="radio"
             name="howMany"
             <?php if (isset($values['howMany']) && $values['howMany'] == "two") echo "checked"; ?>
             value="two">
      两种
    </label>
    <label>
      <input type="radio"
             name="howMany"
             <?php if (isset($values['howMany']) && $values['howMany'] == "twoplus") echo "checked"; ?>
            value="twoplus">
      两种以上
    </label>

    <?php if (in_array('howMany', $errors)): ?>
      <span class="error">数量不能为空</span>
    <?php endif; ?>
  </div>

  <label for="favoriteFruit">我最喜欢的果蔬品种</label>
  <div>
    <select name="favoriteFruit[]" id="favoriteFruit" size="4" multiple="">
      <?php
      $options = ["苹果", "香蕉", "李子", "石榴", "草莓", "西瓜"];
      foreach ($options as $option) {
        printf(
          '<option value="%s" %s>%s</option>',
          $option,
          (in_array($option, $values['favoriteFruit'])) ? "selected" : '',
          ucfirst($option)
        );
      }
      ?>
    </select>
    <?php if (in_array('favoriteFruit', $errors)): ?>
      <span class="error">品种不能为空</span>
    <?php endif; ?>
  </div>

  <label for="brochure">是否需要天宁日记提供的礼品</label>
  <div>
    <input type="checkbox"
           name="brochure"
           id="brochure"
           <?php if (isset($values['brochure']) && $values['brochure'] == "Yes") echo "checked"; ?>
           value="Yes">
  </div>
  <div>
    <input type="submit" name="submit" value="提 交">
  </div>
</form>
</body>
</html>

Guess you like

Origin blog.csdn.net/longv888/article/details/129056252