PHP submitting form with a variable amount of fields with variable names, check if at least one set

StackOverflow https://stackoverflow.com/questions/12379891

Question

Okay so my title might be a little confusing, but let me explain my situation:

I have a pretty big form with lots of fields, some which are required, some which are not. I do validation with JS, but then I'm also doing validation on the server side with PHP.

One of the things I'm asking the user for is a "Header Name". Now, header name has the name attribute of "header1". The user has the option of adding more header fields on the form. So if they click a button it adds another "Header Name X" with name attribute "headerx".

Got it? Now, the problem is, in general these header fields are not required, but I do have the condition that they MUST supply at least one Header field. So they could supply 100, they could supply 2, they might supply 1, but if they don't supply any then validation should fail.

I can't think of a good way of checking for this in PHP though. I know your fist thought is just check if $_POST contains anything. Won't work though because they are multiple other fields in this form that are required that have nothing to do with these Headers. So I can't just simply check to see if $_POST contains something because it always will.

Is there a way I can like combine isset() with a regular expression? Like isset($_POST['header{\d+}']. Which would be saying like header with atleast one digit following it.

Thanks for the help!

EDIT: Oh and if this wasn't hard enough already, the amount of Header Fields is limitless. So I can't just loop through all the possible "headerx" because that would obviously be an infinite loop.

Was it helpful?

Solution

You could have field names with []:

<input type="text" name="foo[]" value="x" />
<input type="text" name="foo[]" value="y" />

Then $_POST would be like:

array('foo' => array('x', 'y'));

You could even have associative arrays:

<input type="text" name="foo[bar][first]" value="x" />
<input type="text" name="foo[bar][second]" value="y" />

Would look like:

array('foo' => array('bar' => array('first' => 'x', 'second' => 'y')))

OTHER TIPS

You can loop through the elements like this:

$i = 1;
while($row = $_POST['header' . $i++]){
    //do stuff
}

this will keep going until there are no more sequential elements.

Why not simply look at it this way: In your JS on the other end, when you are doing validation, have the last check a check to verify that a header is sent - and it it passes, set a hidden field in the form to a true value - then in your PHP you can check that particular element without having to worry about every possible header that is sent.

if(!count(preg_grep('@^header\d+$@',array_keys($_POST))))
{
  //no header submitted
}

This will allow to use a RegExp as requested, but I also would prefer the solution by jpic

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top