0

我正在尝试为表单验证设置简单的示例,无论字段是否为空。如果字段不为空,则将我重定向到页面 ok.php,如果不返回到 formvalidation.php。并更改字段的 css。我在将错误数组返回给 formvalidation.php 并对其进行测试以更改输入字段的 css 时遇到问题。我究竟做错了什么?

表单验证.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>  

动作.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;

}
4

2 回答 2

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()位于代码的顶部

于 2013-05-09T07:35:01.517 回答
0

看看这个教程:http ://www.html-form-guide.com/php-form/php-form-validation.html 。它的实现更加面向对象。

于 2013-05-09T07:42:13.763 回答