Workaround for validation and checking if the form has been actually posted

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-31 07:05:09

问题


Here is my typical form

        $errors = array();

        if ($this->request->post('submit')) { // <----- I don't like this line
            $post = Validation::factory($this->request->post())
                ->rule('email', 'not_empty')
                ->rule('email', 'email')
                ->rule('password', 'not_empty');

            if ($post->check()) {
                // ok, do something
            }

            $errors = $post->errors(true);
        }

        $this->template->content = View::factory('auth/register')
            ->set('errors', $errors);

As you see - I check if there is a submit element which means that we have actually posted form, not just requested for the first show.

If we remove that condition - we will have validation errors for the first page request. The errors about empty email and password form. Which is actually just incorrect.

So how do you solve this issue?


回答1:


This is how I'd do it, except for the condition:

if (Request::POST === $this->request->method())

would be more suitable. There is no way to "skip" the POST check without having consequences (like the errors in your case).

We had a discussion on this topic, 5.3 will probably add more features. Something like:

$this->post(function(){
    // do POST-specific stuff 
})
->get(function(){
    // do GET-specific stuff
});



回答2:


if ($post = $this->request->post())
{
    $post = Validation::factory($post);
    ...
}


来源:https://stackoverflow.com/questions/6201230/workaround-for-validation-and-checking-if-the-form-has-been-actually-posted

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!