使用 PHP 的 Smarty 表单验证
Smarty form validation using PHP
我想在 Smarty 模板上使用 PHP 验证我的表单。我在网上和这里搜索了一些解决方案,但对我来说没有任何效果。如果某些字段为空或填充了不正确的数据,我想留在同一页面上。文件 "result.php" 是正确提交的数据所在的页面。我已经做到了,使用 javascript,但我想知道如何使用 PHP在用户浏览器中禁用 javascript 并进行更复杂的检查 运行(空格、空字段、不正确的字符...)。 posted PHP 脚本不做任何验证,我得到一个未定义的索引:错误。我 post 一段我的代码。请帮忙。提前致谢!
php代码(index.php):
if (!empty($_POST)) {
if (!empty($scrubbed['name']) || !empty($scrubbed['age'])) {
header("Location: result.php");
}
else {
$smarty->assign('error', 'Please fill out the form completely');
$smarty->display('index.tpl');
}
}
聪明的代码(index.tpl):
{$error}
<table width="600" align="center" cellpadding="5">
<form name="infoform" action="result.php" method="post">
<tr>
<td><div align="right">Name:</div></td>
<td><input type="text" name="name" size="20"/></td>
</tr>
<tr>
<td><div align="right">Age:</div></td>
<td><input type="number" name="age" size="2" min="1" max="65"/></td>
</tr>
...
php代码(index.php):
改为重定向,只在此处进行验证:
if (!empty($scrubbed['name']) || !empty($scrubbed['age'])) {
// do something with post data, validate it
}
聪明的代码 (index.tpl):
要避免消息 undefined index: error
,只需执行以下操作:
{if isset($error)}
{* do something here if You have error... *}
{/if}
我想在 Smarty 模板上使用 PHP 验证我的表单。我在网上和这里搜索了一些解决方案,但对我来说没有任何效果。如果某些字段为空或填充了不正确的数据,我想留在同一页面上。文件 "result.php" 是正确提交的数据所在的页面。我已经做到了,使用 javascript,但我想知道如何使用 PHP在用户浏览器中禁用 javascript 并进行更复杂的检查 运行(空格、空字段、不正确的字符...)。 posted PHP 脚本不做任何验证,我得到一个未定义的索引:错误。我 post 一段我的代码。请帮忙。提前致谢!
php代码(index.php):
if (!empty($_POST)) {
if (!empty($scrubbed['name']) || !empty($scrubbed['age'])) {
header("Location: result.php");
}
else {
$smarty->assign('error', 'Please fill out the form completely');
$smarty->display('index.tpl');
}
}
聪明的代码(index.tpl):
{$error}
<table width="600" align="center" cellpadding="5">
<form name="infoform" action="result.php" method="post">
<tr>
<td><div align="right">Name:</div></td>
<td><input type="text" name="name" size="20"/></td>
</tr>
<tr>
<td><div align="right">Age:</div></td>
<td><input type="number" name="age" size="2" min="1" max="65"/></td>
</tr>
...
php代码(index.php):
改为重定向,只在此处进行验证:
if (!empty($scrubbed['name']) || !empty($scrubbed['age'])) {
// do something with post data, validate it
}
聪明的代码 (index.tpl):
要避免消息 undefined index: error
,只需执行以下操作:
{if isset($error)}
{* do something here if You have error... *}
{/if}