views:

40

answers:

3

I need to validate a form in php and display some error messages in the view if there are validation errors. The problem is that once the form is submitted, sending the user back to the page will clear all the of the completed form fields. Is there a simple way to not lose the unvalidated form data?

The only solution I can come up with is reverse engineering the $_POST variable, but I'd like a more elegant way to do it.

Thanks!

+2  A: 

Don't send the user anywhere, but re-render the form right where you are, pre-populating the form with the entered values. That would be the most common method.

The second way would be storing the values in session variables, but that should be the last resort if the project structure doesn't allow for the first approach.

Pekka
+2  A: 

Validate on the client side.
If you must validate on the server side, made an ajax call (so you won't have to refresh the page) to the server with the elements you want to validate. Make the validations you need and return an answer back to the page (is valid or not).
If answer is valid, you can proceed (Note: you may not need to return to the page after the validation, if all the elements you need to proceed are also the ones validated).
If it's not valid, the answer should return the invalid elements (and possibly a error message for each) so that you can display the error messages you want.

lodge
Client side validation usually isn't enough. JavaScript could be turned off. Also, without server side validation, harmful data could enter the system.
Pekka
Client validation is very insecure, I need to check for malicious data on the server side, just like Pekka said, users could turn JS off, or they might fiddle with the view to bypass security checks there.
Cat
+1  A: 

If in php code that you use to prepare the form you always set field values to whatever exists in $_POST array, then in validation code you can simply conditionally include that form file and it will render itself with user values. When you render the form the first time (empty form) $_POST will not have elements with field names, and the form will be empty.

spbfox