Workaround to validate and verify whether the form was actually submitted

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 can see - I am checking if there is a submit element, which means that we actually posted the form, and not just requested for the first show.

If we remove this condition, we will have validation errors for requesting the first page. Errors in blank email and password form. This is actually not true.

So how do you solve this problem?

0
source share
2 answers

Here is how I would do it, except for the condition:

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

will be more appropriate. It is impossible to "skip" the POST check without consequences (for example, an error in your case).

We had a discussion on this topic, 5.3 is likely to add more features. Sort of:

$this->post(function(){
    // do POST-specific stuff 
})
->get(function(){
    // do GET-specific stuff
});
+3
if ($post = $this->request->post())
{
    $post = Validation::factory($post);
    ...
}
+1

All Articles