We help IT Professionals succeed at work.
Get Started

PHP Function based on css class="required"

DennisHacker
DennisHacker asked
on
273 Views
Last Modified: 2012-08-26
I have a dynamic form that shows and hides table rows containing inputs on a form with javascript.  It also changes the class attribute for each of the input elements in a visible row to "required".

On smaller forms, I set up an array called $formElements that lists every element on the form.  If the form is submitted, I run the htmlspecialchars function on the element, and then have individual if statements that check if the $_POST variable for the element is blank, generate an error, and set a $valid_form variable to FALSE, preventing the submission of the form.

As you can imagine, as the form grows in numbers of variables, that list is repetitive, and very long.  Additionally, it's not practical, because if a row is not visible, I don't want the elements in that row to be required.

I would like to write a php function that would:
apply the htmlspecialchars function to the $_POST of each variable
if class="required" and the $_POST of the variable = "", then set the $error['element'] = $error_open . "Please fill in required field." . $error_close;  and set the $valid_form variable to FALSE.

Is this a place where a function is best used?  If so, can one function be used for both purposes?

HERE IS A PORTION OF THE CODE THAT I'M USING SO FAR...

if (isset($_POST['submit']))
{
	// process form
	
	// get form data
	foreach ($form_elements as $element)
	{
		$form[$element] = htmlspecialchars($_POST[$element]);
	}
	
	// check form elements
		// check required fields
		if ($form['organizerName'] == '')
		{
			$error['organizerName'] = $error_open . "Please fill in all required fields!" . $error_close;
			$valid_form = FALSE;
		}
		if ($form['organizerPhone'] == '')
		{
			$error['organizerPhone'] = $error_open . "Please fill in all required fields!" . $error_close;
			$valid_form = FALSE;
		}

ETC., ETC. FOR EACH OF THE FORM ELEMENTS

Open in new window

Comment
Watch Question
This problem has been solved!
Unlock 1 Answer and 3 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE