使用PHP进行表单输入字段验证


Form input field validation with PHP

我在<form>中有几个字段。。。$fieldset是字段名称的数组,它用isset()检查来循环它们。

我想对几个字段应用验证(例如:必填输入、电子邮件),如何从我的代码逻辑中应用它?

public function actionProfile($id = null) {
        $profileModel = new ProfileModel;
        // <input> fields name
        $fieldset['name'] = array('FirstName', 'LastName');
        $fieldset['address'] = array('HouseNumber', 'StreetName', 'Town', 'Location');
        $formError = array();
        if (isset($_POST['profile'])) {
            // Process input event
            foreach ($fieldset as $legend => $fields) {
                foreach ($fields as $field) {
                    if (!isset($_POST['profile'][$field])) {
                        $formError[$legend] = $field;
                    } else {
                        $form[$legend][$field] = $_POST['profile'][$field];
                    }
                }
            }
            if (count($formError) == 0) {
                if ($profileModel->saveAddress($form['address'])) {
                    //Saved to the database.
                }
            } 
        }

       // Get data from the database
       $data['profile'] = $profileModel->find($id);
       $view = new View($this->layout, $data)->render();
}

在视图文件中,它看起来像这样:

<input type='text' value=<?php echo $profile['first_name'] name='profile[FirstName]' ?>
<input type='text' value=<?php echo $profile['last_name'] name='profile[LastName]' ?>

编辑:通过表单编辑记录时。如果出现错误(验证),我希望将用户输入值放回<input>值,而不是数据库中的值。如何从我的代码中完成?

您当前正在将验证逻辑放入控制器中。这应该在域业务对象中(阅读更多:此处和此处)。

此外,"模型"不是一个类。模型是MVC体系结构中的一层。该层主要由两种类型的实例组成:域对象和数据映射器。每个人都有着截然不同的责任。

我认为从实际的更新函数中分离验证代码是明智的。

让它首先通过验证器运行,检查长度和所需的输入。当它通过时,您可以将所有(格式化的)数据发送到操作。如果它没有通过验证,请将它返回到带有其他错误信息的视图,以便指导用户解决问题。

我希望你能理解我想向你解释的内容。

使用PHP Filter函数:

http://www.php.net/manual/en/ref.filter.php

使用可变处理程序

http://us2.php.net/manual/en/ref.var.php