【问题标题】:How to get the name of input field with PHP如何使用 PHP 获取输入字段的名称
【发布时间】:2020-10-23 12:24:22
【问题描述】:

我正在尝试创建一个函数。这将检查该字段是否为空。如果输入为空,则会在错误数组中推送该输入的错误。

$errors = ["name" => "Name is required"];

像这样

我该怎么做?

function checkRequiredFields($fields = [], $errors = [])
{
  foreach ($fields as $field) {
    if (is_blank($field)) {
      $errors[$field] = "$field is required";
    }
  }
}

顺便说一句,这是我的 is_blank 函数的外观:

function is_blank($value)
{
  return !isset($value) || trim($value) === '';
}

【问题讨论】:

  • 所以您正在寻找 is_blank() 的实现?
  • (我的观点是:以这种方式进行验证有点笨拙,因为它对所有字段进行相同的检查。如果您想要对某些字段进行其他检查,您会得到一堆不可读的 if 子句,或类似的。)
  • 给定的代码有什么不工作的地方吗?

标签: php forms post


【解决方案1】:

您可以检查该字段是否已提交并且不包含空字符串:

<?php

function check_required_fields($fields, &$errors) {
    foreach($fields as $fieldname) {
        if(isset($_POST[$fieldname]) && $_POST[$fieldname] === '') {
            $errors[$fieldname][] = "'$fieldname' is required.";
        }
    }
}
check_required_fields(['email'], $errors);
?>
<form method='POST'>
    <input type='text'  name='name'>
    <input type='email' name='email'>
    <input type='submit'>
</form>

【讨论】:

    【解决方案2】:

    您可以使用

    获取输入字段的值

    $field = $_GET["field"]; // or $_POST["field"]; 取决于您的表单。

    但出于安全原因,您需要正确清理输入值。

    https://www.php.net/manual/fr/function.filter-input.php

    empty() 函数也是你要找的。​​p>

     if (empty($field)) {
      $errors[$field] = "$field is required";
    }
    

    查看文档:https://www.php.net/manual/fr/function.empty.php

    也看看 isset() 函数。

    【讨论】:

    • 根本没有回答我的问题。
    • 我没有使用empty(),因为如果值为0,它会返回true。
    猜你喜欢
    • 2023-03-09
    • 2014-04-09
    • 1970-01-01
    • 1970-01-01
    • 2012-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多