简体   繁体   中英

Server-side validation and form action

I have a page (call it ) 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 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 with the fields the user needs to fix highlighted. If the form passes validation, I want to go to another page, .

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?

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM