简体   繁体   中英

How to Validate Dynamic form with PHP?

I have searched over SO for quite awhile so I apologize if a similar question is asked and answered but I don't believe there is.

I am using a PHP validation script and jQuery Validate to process all of the forms on my site. With known fields, no issues. However, there are pages which a user can enter additional person(s) information.

A user is asked to enter his family member's names in a form. The user can submit the form or choose to add additional family members to the form. I have not quite figured out how to properly cycle through all the fields and display unique messages based on the users input in jQuery but know I can do so with metadata and the validation plugin.

My issue lies with PHP. I can take each array and run though foreach loops, however, if an error is found in ANY field, an error is generated and the form is displayed again with all fields' previously entered data. I am unable to determine how to point each field's original data to it given the fields are built dynamically when errors appear.

The SIMPLEST METHOD I can come up with for demonstration is this:

A user must enter the percentages of pie he wants his friends to eat. He must give out 100% of his pie. The user can choose to dynamically add friends to his pie eating extravaganza but each person must receive atleast 1% of the pie and they must all together eat 100%.

Sample code

I have created a sample script here which shows the form setup but obviously there is no PHP backend to test. You will need to use your imagination the backend works (I have added into the comments in the html). The same principle would apply with PHP SESSION variable since this data would need to be passed from page to page (if a user revisits this page, the amounts entered for each piece of pie should display). Also, I think it goes without saying but this data MUST BE validated server-side.

Will you not be reloading the page in the event of a PHP error? In which case you know the index of the error in the foreach loop, saved off to some variable - most likely an array to handle multiple errors. When you print the options back out and you are looping through the submitted array again can you not add an additional css class to the text box when you reach a count that is in your error array.

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