phenry
phenry

Reputation: 2067

Server-side validation and form action

I have a page (call it form.php) with a form for users to fill out. When the form is submitted, I want to validate it with a server-side script (call it validate.php if necessary, although the code could also go in one of the other pages if that would be better). If any part of the form fails validation, I want to kick back to form.php with the fields the user needs to fix highlighted. If the form passes validation, I want to go to another page, success.php.

Which page should I put in the "action" attribute of the <form> element, and what's the best way to get from that page to one of the others?

Upvotes: 0

Views: 859

Answers (3)

Fabrizio D&#39;Ammassa
Fabrizio D&#39;Ammassa

Reputation: 4769

I suggest the approach used by Magento.

You have a formAction method in your controller that displays the form, then another action formPostAction that handles the form submission.

If the validation fails for example, you should create a proper error message, then store in the session an array with the form data just submitted and redirect to the form page.

The formAction() method should have a bit of logic to handle data in session, cleaning those once used for the output, to avoid security issues.

Upvotes: 1

Abdullah Jibaly
Abdullah Jibaly

Reputation: 54820

I would have the action be form.php (same as the display page). In the PHP check if the request is a GET or a POST. If it is a GET simply display the blank form. If it's a POST validate the response, and if it is valid REDIRECT to success.php. If it is not valid render the form again (form.php) with the errors highlighted inline.

Upvotes: 1

Rudu
Rudu

Reputation: 15892

There's lots of answers to this, it's a bit of a style thing. I'd post form.php -> form.php. If it passes validation then it can display the content of success.php, if it fails, it can show the same form again with the updated values. If the updated URL is key to your application workflow, you could always use a URL redirection after validation is successful.

Upvotes: 2

Related Questions