【问题标题】:Array Validation数组验证
【发布时间】:2016-02-13 12:02:40
【问题描述】:

我正在尝试学习验证,下面是用户输入验证用户输入所需的 4 个字段的表单。

第一个问题:对于变量 $a 来检查错误数组中是否有内容,我应该在哪里定义它?

第二个问题:对于每个字段(productname/desc/cat/price),我应该创建一个不同的数组来存储错误消息吗?

<?php

$productName = filter_has_var(INPUT_GET, 'pName') ? $_GET['pName']: null;
$desc = filter_has_var(INPUT_GET, 'description') ? $_GET['description']: null;
$cat = filter_has_var(INPUT_GET, 'category') ? $_GET['category']: null;
$pPrice = filter_has_var(INPUT_GET, 'price') ? $_GET['price']: null;

$productName = trim ($productName);
$desc = trim ($desc);
$cat = trim ($cat);
$pPrice = trim ($pPrice);

echo "<h1>Product details</h1>\n";

$nameerror = array();

if (empty($productName))
{ 
$nameerror[] = "You have not enter a Product";
}
elseif (strlen($productName) >50)
{
$nameerror[] = "Exceed product field length"; 
}
if (empty($desc))
{ 
$nameerror[] = "You have not enter description in the Description field";
}
elseif (strlen($desc) >100)
{
$nameerror[] = "Exceed descrption field length"; 
}
if (empty($cat))
{ 
$nameerror[] = "You have not enter category in the Category field";
}
if (empty($pPrice))
{ 
echo"<p>You have not enter price in the Price field</p>\n";
}
elseif (strlen($pPrice) >10)
{
echo"<p>Exceed price field length</p>\n"; 
}

if (!empty($nameerror))
for ($a=0;$a<count($nameerror);$a++)
{
    echo "$nameerror[$a] <br />\n";
}
else
{
echo "<p>Name: $productName</p>\n";
echo "<p>Description: $desc</p>\n";
echo "<p>Category: $cat</p>\n";
echo "<p>Price: $pPrice</p>\n";
}

?>

【问题讨论】:

  • $errors 未定义..
  • 请参阅this 回答,了解如何验证和清理输入字段。

标签: php arrays validation


【解决方案1】:

您的目标是收集表单中的所有错误并告诉用户这些错误。

除了你在循环中使用了错误的数组名之外,一切都是正确的。应该是:

for ($a=0;$a<count($nameerror);$a++)
{
    echo "$nameerror[$a] <br />\n";
}

您的第二个问题的答案是:不,您可以将所有错误消息存储在一个数组中,就像您已经完成的那样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-27
    • 2019-12-26
    • 2020-05-07
    • 2019-02-21
    • 2015-10-24
    • 2018-01-03
    • 2021-09-08
    相关资源
    最近更新 更多