【问题标题】:function to check required form fields not working检查所需表单字段的功能不起作用
【发布时间】:2013-09-12 00:24:29
【问题描述】:

我有一个用户定义的函数,它需要一个参数作为表单必填字段的数组。它检查这些字段是否为空。如果它们为空,它将返回一条消息并停止处理表单。

<?php

function check_required_fields($required_array) {
    foreach($required_array as $fieldname) {
        if (!isset($_POST[$fieldname]) || (empty($_POST[$fieldname]) && $_POST[$fieldname] != 0)) { 

        }
    }
    return "You have errors";
}
$required_array = array('name', 'age');
if (isset($_POST['submit'])) {
    echo check_required_fields($required_array);
}
?>

<html>
<body>

<form action="#" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="age"><br>
<input type="submit" name="submit">
</form>

</body>
</html>

即使填写了表单必填字段,该函数仍返回此错误?如何解决这个问题? 我怎样才能使用只使用该功能而不在其名称前写单词 echo?

我想使用这个功能,所以我不必为表单中的每个字段手动编写 if 和 else 语句。

【问题讨论】:

  • 返回需要在 if 子句中
  • 你可以直接使用if(empty($fieldname)) return false;,其他控件没用,我直接把$_POST传给函数check_required_fields($_POST)
  • 我想显示空字段的自定义错误。

标签: php forms


【解决方案1】:

我想你想这样做?

function check_required_fields($required_array) {
    foreach($required_array as $fieldname) {
        if (!isset($_POST[$fieldname]) || (empty($_POST[$fieldname]) && $_POST[$fieldname] != 0)) { 
            return "You have errors"; //This indicates that there are errors
        }
    }
}

或者为什么不只是:

function check_required_fields($required_array) {
    foreach($required_array as $fieldname) {
        if (!isset($_POST[$fieldname])) { 
            return "You have errors"; //This indicates that there are errors
        }
    }
}

更新:

变化:

$required_array = array('name', 'age'); //This just sets strings name and age into the array

到:

$required_array = array($_POST['name'], $_POST['age']); //This takes the values from the form

【讨论】:

  • 我尝试了第二个建议的代码,它没有输出任何错误信息?我完全理解您对代码的更改和建议。但它不起作用。
  • 它有效。我怎样才能在每一行返回一个空的 $fieldname ?示例:返回 $fieldname 。 "是必需的
    ";我试过这个它不起作用。
猜你喜欢
  • 1970-01-01
  • 2016-04-17
  • 1970-01-01
  • 2021-01-20
  • 2013-02-13
  • 1970-01-01
  • 2012-07-22
  • 2020-03-06
  • 2015-12-07
相关资源
最近更新 更多