【发布时间】: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