phpformsissetname-attribute

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


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.


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')))