【问题标题】:How to check user textbox is empty effectively? [duplicate]如何有效地检查用户文本框是否为空? [复制]
【发布时间】:2018-01-26 01:50:11
【问题描述】:

我正在尝试制作一个 PHP 表单并检查文本框是否为空。我的代码:

<form method="post"> 
  Name: <input type="text" name="name">
  <span class="error">* <?php echo $nameErr;?></span>

//check user that fill in blank
if (empty($_POST["name"])) {
   $nameErr = "Name is required";
   }

这是检查用户是否填写空白的有效方法吗? 如果用户键入“0”,系统将显示错误消息。

有人有更有效的方法吗?

【问题讨论】:

  • 试试 !isset OR empty()

标签: php forms


【解决方案1】:

如果用户输入“0”,系统会显示错误信息

使用filter_var(),更准确地说是FILTER_VALIDATE_INT

看看里面的cmets:

$input = 0; // is an integer and will not echo

if(filter_var($input, FILTER_VALIDATE_INT) === false){
  echo "The input is not an integer";
}

$input = "0"; // is an integer and will not echo

if(filter_var($input, FILTER_VALIDATE_INT) === false){
  echo "The input is not an integer";
}

$input = "text"; // is NOT an integer and will echo

if(filter_var($input, FILTER_VALIDATE_INT) === false){
  echo "The input is not an integer";
}

$input = "text123"; // is NOT an integer and will echo

if(filter_var($input, FILTER_VALIDATE_INT) === false){
  echo "The input is not an integer";
}

至于你的:

这是检查用户是否填空的有效方法吗?

  • empty() 在这里工作得很好,因为 isset() 与收音机/复选框更有效。

看看以下内容以及两者之间的区别:

【讨论】:

    【解决方案2】:

    问题是以下值被认为是“empty()”:

    "" (an empty string)
    0 (0 as an integer)
    0.0 (0 as a float)
    "0" (0 as a string)
    NULL
    FALSE
    array() (an empty array)
    

    因此,在验证变量是否实际包含数据时,除了empty(),您还需要检查isset()

    if (empty($_POST["name"]) || !isset($_POST["name"])) {
      $nameErr = "Name is required";
    }
    

    希望这会有所帮助! :)

    【讨论】:

    • "0" 仍然会触发您的错误
    【解决方案3】:

    你可以使用trim(),它会删除开头或结尾的空格,所以它也会删除一个空格

    if (empty(trim($_POST["name"]))) {
      $nameErr = "Name is required";
    }
    

    或(避免“0”问题)

    if (trim($_POST["name"]) !== "") {
      $nameErr = "Name is required";
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-09
      相关资源
      最近更新 更多