douxiu6835 2012-03-13 10:47
浏览 38

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

I have a couple of fields in the <form>... $fieldset is array of the fields name, it loop them with isset() checking.

I want to apply validation (eg: required input, email) to a few fields, how to apply this from my code logic?

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();
}

In the view file, it would look something like this:

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

Edit: When editing the record via form.. If there is an error (validation) - I want to put user input value back into <input> value instead of value from the database. How can it be done from my code?

  • 写回答

3条回答 默认 最新

  • dqqn32019 2012-03-13 11:43
    关注

    I think it would be wise to split the verification code from the actual update function.

    Have it run through a validator first, checking for length and required inputs. When that passes, you can send all that (formatted) data to the action. If it doesn't pass the validation, return it to the view with additional error information so you can guide the user to fix the problem.

    I hope you understand what I'm trying to explain to you. :-).

    评论

报告相同问题?

悬赏问题

  • ¥15 基于单片机数字电压表电路组成及框图
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line