验证while循环

i want to validate a form which contains of several input fields. most of them a simply text/numbers and work fine.

for one part of the form i create several fields ('year' and 'text') and duplicate them via a while loop.

it look like this:

<?php while ($mcount <= 10):?>
<h4><?= __("Moment") ?> <?= $mcount ?></h4>
<div class="row">
    <label for="year_<?= $mcount ?>"><?= __("Year") ?></label>
    <input name="year_<?= $mcount ?>" value="" ></input>
    <span class="error">Error Message for this particular Year</span>
</div>
<textarea name="text_<?= $mcount ?>" maxlength="400"></textarea>
<span class="error">Error Message for this particular Textarea</span>
<?php $mcount++; ?>

i try to validate the form with this:

$texts = [ 'text_1', 'text_2', 'text_3', 'text_4', 'text_5', 'text_6', 'text_7', 'text_8', 'text_9', 'text_10',];
    foreach ($texts as $mText) {
        if (empty($_POST[$mText])) {
            $errors[] = 1;
            echo "missingtext". $mText ;
        }
    }

my problem is to create a variable in the validation which is responsible for the error message for a particular year/text. and how to output this variable in the while loop.

as special feature it might happen that parts of the 10 moments are created by a foreach loop – which is filled by a processwire repeater field.

thanks for any help!

Just do the sensible thing and go with PHP arrays:

<?php while ($mcount <= 10):?>
<h4><?= __("Moment") ?> <?= $mcount ?></h4>
<div class="row">
    <label for="year[<?= $mcount ?>]"><?= __("Year") ?></label>
    <input name="year[<?= $mcount ?>]" value="" ></input>
    <span class="error">Error Message for this particular Year</span>
</div>
<textarea name="text[<?= $mcount ?>]" maxlength="400"></textarea>
<span class="error <?= isset($errors[$mcount])?"":"hidden" ?>">Error Message for this particular Textarea</span>
<?php $mcount++; ?>

Then in code it's a matter of

foreach ($_POST["text"] as $ind => $mText) {
    if (empty($mText)) {
        $errors[$ind] = 1;            
    }
}

And have a style:

.hidden { display: none; }

The docs have more info on creating arrays in an HTML form

Define your array outside of the loop,

$texts = [ 'text_1', 'text_2', 'text_3', 'text_4', 'text_5', 'text_6', 'text_7', 'text_8', 'text_9', 'text_10',];
$errors = [];

What this does is prevents the array from being overwritten on each iteration.

Then in the loop add,

array_push($errors, mText . ' cannot be empty.');

What this does is adds a new error to the array.

Then once the loop is complete,

if (!empty($errors)) {
    foreach($errors as $error) {
        echo $error;
    }
}

What this does is loop through the errors if the $errors is NOT empty (so if an error exists).

Reading Material

array_push