表单验证:如何使用PHP为用户提供特定的反馈?

时间:2014-04-02 19:30:19

标签: php forms validation

我有一个包含3个输入框,1个单选按钮,3个下拉列表以及提交按钮的表单。

1下拉框必须是整数输入& 1必须是字母。

我目前已经设置了非常基本的验证功能,可以:

1)检查是否已为所有必填字段提供了一些数据。 2)检查一个输入框是否仅为整数。 3)检查另一个是否只是字母。

如果省略任何输入,我可以输出错误。我试图做的是确定哪个 字段被遗漏,并向用户提供相关权利的更具体的反馈 字段

这是迄今为止的代码(它可能不是最有效的解决方案):

if (isset($_POST['submit'])){
            $submit = ($_POST['submit']);

            $title = $_POST['title'];
            $duration = $_POST['duration'];
            $director = $_POST['director'];


            /*if (isset($_POST['cert'])){
            echo "cert set: ".$_POST['cert'];
            }*/



            //If any of the (title, duration, director) are empty or if any of the (day, month, year) are unchanged or if the cert isn't set i.e radio button checked
            //Error
            if (empty($title) || empty($duration) || empty($director) || !isset($_POST['cert']) || ($_POST['day'] == "DD") || ($_POST['month'] == "MM") || ($_POST['year'] == "YYYY")){

                    echo "Error";

            } else {

                        //Check if duration entered is an integer
                        if (is_int($duration) && ctype_alpha($director)) {

                                $cert = $_POST['cert'];
                                $day = $_POST['day'];
                                $month = $_POST['month'];
                                $year = $_POST['year'];
                                $day = convertToTwoDigit($day);
                                $month = convertToTwoDigit($month);
                                $year = convertToTwoDigit($year);


                                $date = $year."/".$month."/".$day;


                                echo "<br>Title: ".$title."</br>"."Duration: ".$duration."</br>"."Director: ".$director."</br>"."Cert: ".$cert."</br>Relesed on: ".$date;

                                //Add values into database: 

                                if ($insert = $db->query("
                                INSERT INTO titles (cert, filmtitle, releaseDate, filmDuration, director) VALUES ('$cert', '$title', '$date', '$duration', '$director')
                                ")){
                                    echo "You have added a film";
                                } else {
                                    echo "Error adding";
                                }
                    } else {
                                echo "director or duration error";
                    }
        }


}

需要什么才能使验证更具体。 某种阵列会起作用吗?

1 个答案:

答案 0 :(得分:0)

有大量现成的PHP表单验证器,例如Easiest Form validation library for PHP?。我建议研究像Laravel和Symfony这样的框架;它们易于使用,并且减少了许多样板,如验证,路由,模板等。

为了学习(听起来你并不熟悉数组),验证器就是这样的,但功能整齐地封装在一个类中:

// Required items
$required = array('title'       => array('type'     => 'alpha',
                                         'message'  => 'Title is required and must be alphabetic'), 
                  'duration'    => array('type'     => 'int',
                                         'message'  => 'Duration is required and must be numeric'), 
                  'director'    => array('type'     => 'alpha',
                                         'message'  => 'Director is required and must be alphabetic')); 

$_POST = array('title' => 'Unforgiven', 'duration' => '2 hours', 'director' => 'Clint Eastwood');
// 'duration' will be invalid because it must be an integer but (obviously) contains alpha characters

// Remove empty items
$post = array_filter($_POST);

$invalid = array();

// Loop required items, checking to see that a) they are in the array and b) their values match your criteria
foreach ( $required as $k => $v ) {
    // Element is empty or not set
    if ( !isset($post[$k]) ) {
        $invalid[$k] = $v['message'];
        continue;
    }
    if ( $v['type'] == 'alpha' && preg_match('/[a-zA-Z ]$/i', $post[$k]) ) {
        // Only letters and spaces
        continue;
    } else if ( $v['type'] == 'int' && preg_match('/[0-9]$/', $post[$k]) ) {
        // Only integers
        continue;
    }
    $invalid[$k] = $v['message'];
}

var_dump($invalid);

然后,您将$ invalid的内容传递回生成表单的文件,并使用该数据向用户输出消息。