【问题标题】:How do I check required fields using 'empty' in a field whose value is an integer?如何在值为整数的字段中使用“空”检查必填字段?
【发布时间】:2014-06-30 02:08:04
【问题描述】:

我正在尝试检查我使用empty 函数的必填字段。不幸的是empty 认为 0 为空,我的值可能是 0 和单选按钮中的 1。我试过使用!is_int(myvalue),但它没有用。

这是我的代码:

  <?php   $required_fields = array('menu_name', 'position', 'visible');
    foreach($required_fields as $fieldname) {
        if(!isset($_POST[$fieldname]) || (empty($_POST[$fieldname]) && !is_int($_POST[$fieldname]))) {
            $errors[] = $fieldname;
        } 
    }
?>

【问题讨论】:

  • 你认为什么是空值?
  • $_POST 如果设置了值,则它们始终是字符串,请尝试将其与空字符串进行检查。 !isset($_POST[$fieldname]) &amp;&amp; $_POST[$fieldname] != ''
  • 是的!这行得通。我在观看的教程中看到了我发布的代码,但它对我不起作用。
  • 我不明白你为什么同时使用empty和isset?使用isset() 检查变量是否已定义。如果是,请使用is_numeric() 确保它是数字。
  • 谢谢。这是我正在观看的视频教程中的一个视频教程,其中is_int 正在使用中。

标签: php validation radio-button


【解决方案1】:

您似乎想测试一个字符串以查看它是否为整数。

尝试使用 is_numeric

http://www.php.net/manual/en/function.is-numeric.php

【讨论】:

    【解决方案2】:
    if(!isset($_POST[$fieldname])  // not in the post
       || (empty($_POST[$fieldname]) && 0 != $_POST[$fieldname]) // empty but not zero
       || (int) $_POST[$fieldname] == '')) // not an integer
    ) {
      $errors[] = $fieldname;
    } 
    

    【讨论】:

      猜你喜欢
      • 2013-07-02
      • 1970-01-01
      • 2018-11-19
      • 1970-01-01
      • 2023-03-11
      • 2023-04-01
      • 2020-01-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多