【问题标题】:How to check if required fields are filled in or not?如何检查必填字段是否填写?
【发布时间】:2021-07-15 16:58:42
【问题描述】:

只使用核心 PHP 而没有其他,比如 JavaScript 或客户端编程,我需要 PHP 来检查表单的必填字段是否已填写,如果未填写则显示错误消息。我需要检查使用过程式编程,因为我还没有进入 OOP 并且不理解它。

HTML 表单

<html>
<head>
<title>
Searchengine Result Page
</title>
</head>
<body>

<form method = 'POST' action = "">
<label for='submission_id'>submission_id</label>
<input type='text' name='submission_id' id='submission_id'>
<br>
<label for='website_age'>website_age</label>
<input type='text' name='website_age' id='website_age'>
<br>
<label for='url'>url</label>
<input type='url' name='url' id='url' required>
<br>
<label for='anchor'>anchor</label>
<input type='text' name='anchor' id='anchor' required>
<br>
<label for='description'>description</label>
<input type='text' name='description' id='description' required>
<br>
<label for='keyphrase'>keyphrase</label>
<input type='text' name='keyphrase' id='keyphrase' required>
<br>
<label for='keyword'>keyword</label>
<input type='text' name='keyword' id='keyword' required>
<br>
<button type='submit'>Search!</button>
</form>
</body>
</html>

Php 表单验证器

<?php
$ints_labels = array('submission_id','website_age');
$strings_labels = array('url','anchor','description','keyphrase','keyword');
$required_labels = array('url','anchor','description','keyphrase','keyword');

$required_labels_count = count($required_labels);

for($i=0; $i!=$required_labels_count; $i++)
{
    if(!ISSET(in_array(($_POST['$required_labels[$i]']),$required_labels))) //Incomplete line as I     don't know how to complete the code here.
    {
        echo 'You must fill-in the field' .'Missed field\'s label goes here'; //How to echo the missed field's label here ?
    }
}

?>

我知道我需要检查关联的数组值,因为这样会更容易且代码更少,但我不知道该怎么做。 注意我的错误回声。它不完整,因为我不知道如何编写代码的平静。 您将如何使用程序样式检查尽可能短的代码? 还有什么我需要知道的吗?

注意:我不想手动输入每个$_POST[] 来检查是否填写了所需的内容。我需要 PHP 循环遍历 $required_labels[] 数组并检查。或者,如果您知道任何更短的不循环检查方法,那么我想知道。

【问题讨论】:

  • 给定的代码有什么不工作的地方吗?您尝试过什么来解决问题?

标签: php html required


【解决方案1】:

首先我们将有一个空的$errors 数组,然后我们将应用验证,如果其中任何一个失败,我们将填充$errors

最后使用辅助函数errorsPrinter,我们将在其标签下打印错误。

对于您的 PHP 验证部分,请使用以下代码。请注意,我还添加了验证 stringint 类型的部分。

<?php

$ints_labels = array('submission_id','website_age');
$strings_labels = array('url','anchor','description','keyphrase','keyword');
$required_labels = array('url','anchor','description','keyphrase','keyword');

$inputs = $_POST;
$errors = [];

foreach($required_labels as $label) {    
    if(!isset($inputs[$label]) || empty($inputs[$label])) {
        $errors[$label] = array_merge(
            ["You must fill-in the field."],
            $errors[$label] ?? []
        );
    }
}

foreach($strings_labels as $label) {    
    if(isset($inputs[$label]) && !empty($inputs[$label]) && !is_string($inputs[$label])) {
        $errors[$label] = array_merge(
            ["This input should be string"],
            $errors[$label] ?? []
        );
    }
}


foreach($ints_labels as $label) {    
    if(isset($inputs[$label]) && !empty($inputs[$label]) && !is_int($inputs[$label])) {
        $errors[$label] = array_merge(
            ["This input should be int"],
            $errors[$label] ?? []
        );
    }
}


function errorsPrinter($errors, $key)
{
    $output = '<ul>';

    if(!isset($errors[$key])) {
        return;
    }
    foreach($errors[$key] as $error) {
        $output = $output. '<li>' . $error . '</li>';
    }

    print($output . '</ul>');
}
?>

在表单中,您可以执行以下操作:

<form method='POST' action="">
    <?php errorsPrinter($errors, 'submission_id') ?>
    <label for='submission_id'>submission_id</label>
    <input type='text' name='submission_id' id='submission_id'>
    <br>
    <?php errorsPrinter($errors, 'website_age') ?>
    <label for='website_age'>website_age</label>
    <input type='text' name='website_age' id='website_age'>
    <br>
    <?php errorsPrinter($errors, 'url') ?>
    <label for='url'>url</label>
    <input type='url' name='url' id='url' >
    <br>
    <?php errorsPrinter($errors, 'anchor') ?>
    <label for='anchor'>anchor</label>
    <input type='text' name='anchor' id='anchor' >
    <br>
    <?php errorsPrinter($errors, 'description') ?>
    <label for='description'>description</label>
    <input type='text' name='description' id='description' >
    <br>
    <?php errorsPrinter($errors, 'keyphrase') ?>
    <label for='keyphrase'>keyphrase</label>
    <input type='text' name='keyphrase' id='keyphrase' >
    <br>
    <?php errorsPrinter($errors, 'keyword') ?>
    <label for='keyword'>keyword</label>
    <input type='text' name='keyword' id='keyword' >
    <br>
    <button type='submit'>Search!</button>
</form>

请注意,errorsPrinter 只是一个助手,您可以删除它并根据需要使用$errors 数组。错误的示例输出如下:

[
    "url" => ["You must fill-in the field."],
    "anchor" => ["You must fill-in the field."],
    "description" => ["You must fill-in the field."],
    "keyphrase" => ["You must fill-in the field."],
    "keyword" => ["You must fill-in the field."],
    "website_age" => ["This input should be int"]
]

【讨论】:

    【解决方案2】:
    $errors = [];    
    foreach($required_labels as $field) {
      if (!isset($_POST[$field]) || $_POST[$field] == '') {
        $errors[$field] = "{$field} cannot be empty";
        // echo "${field} cannot be empty";
      }
    }
    

    然后输出那些错误:

    <?php 
    if (count($errors)) {
    ?>
      <div id='error_messages'>
        <p>Sorry, the following errors occurred:</p>
        <ul>
        <?php
        foreach ($errors as $error) {
          echo "<li>$error</li>";
        }
        ?>
        </ul>
      </div>
    <?php
    }
    

    您也可以直接在输入旁边输出错误:

    <input type="text" id="first_name" name="first_name" placeholder="First Name" />
    <?php if (isset($errors['first_name'])) echo "<div class='error_message'>{$errors['first_name']}</div>";?>
    

    【讨论】:

    • 你的答案是正确的,但它是不可扩展的。你有 $errors 数组,但它只包含必需的错误,如果你想做更多的检查并收集更多的错误,我认为他打算这样做。
    • 您好 jshrc,您的代码看起来不错,但系统会自动标记其长度。你能添加一些解释你在这里做了什么吗?也许可以解释一下你可以用$errors 数组做什么(即使对于更有经验的读者来说很明显)。 :)
    猜你喜欢
    • 1970-01-01
    • 2010-09-28
    • 1970-01-01
    • 2019-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-02
    相关资源
    最近更新 更多