我正在尝试设置表单验证的简单示例,无论字段是否为空。如果字段不为空,则操作会将我重定向到页面ok.php,如果没有返回到formvalidation.php。并改变该领域的CSS。我有问题将错误数组返回到formvalidation.php并测试它以更改输入字段的css。我做错了什么?
formvalidation.php
<?php require("includes/functions.php"); ?>
<?php
global $errors;
?>
<form action="posting.php" method="p">
<ul>
<li id="field">
<label for="field">Contact person </label>
<input
<?php
if (empty($errors)) {
echo "style=\"background-color: #ECECEC;\"";
} else {
if (in_array("field", $errors)) {
echo "style=\"background-color: red;\"";}
} else {
echo "style=\"background-color: #ECECEC;\"";
}
}
?>
type="text" name="field"/>
</li>
<li>
<input id="saveForm" class="button_text" type="submit" name="submit" value="Submit" />
</li>
</ul>
</form>
action.php的
<?php require("includes/functions.php"); ?>
<?php
$errors = form_validation ();
if (!empty($errors)) {
redirect_to("formvalidation.php");
} else {
redirect_to("ok.php");
}
?>
功能
<?php
function form_validation () {
$errors = array ();
$required_fields = array('field');
foreach($required_fields as $fieldname) {
if (!isset($_POST[$fieldname]) || empty($_POST[$fieldname])) {
$errors[] = $fieldname;
}
}
return $errors;
}
答案 0 :(得分:0)
重定向$error
变量为空后,请使用$_SESSION
<?php
$_SESSION['error']=form_validation ();
if (!empty($_SESSION['error'])) {
redirect_to("formvalidation.php");
} else {redirect_to("ok.php");}
?>
并在formvalidation.php中
$error=$_SESSION['error'];
unset($_SESSION['error']);
不要忘记确保session_start()
位于代码顶部
答案 1 :(得分:0)
请看一下本教程:http://www.html-form-guide.com/php-form/php-form-validation.html。它的实现更加面向对象。