Carlos Charles
Carlos Charles

Reputation: 25

PHP arrays validation

I have a form that gets validated when submit. I make sure some fields are not empty, date fields have a valid format, etc. I have a block of check boxes with a text input next to it.

Option 1
<input type="checkbox" name="jobBonusId[]" value="1"  />
Option 2
<input type="checkbox" name="jobBonusId[]" value="2"  />
Option 3
<input type="checkbox" name="jobBonusId[]" value="3"  />

Amount 1
<input type="number" name="jobBonusAmount[]" step="0.01" value="0.00" />
Amount 2
<input type="number" name="jobBonusAmount[]" step="0.01" value="0.00" />
Amount 3
<input type="number" name="jobBonusAmount[]" step="0.01" value="0.00" />

So, if any of the jobBonusId[] checkbox gets checked it creates an array. Now, I want to validate the jobBonusAmount[] if its -parent- checkbox was checked and make sure is not empty or equals 0.00.

So far, I have the following code:

// Run the script
if (isset($_POST['addJobRecord']) && $_POST['addJobRecord']=='oTzm50xfm') {
   // Validate date format
   if (!validateDate($jobDateStart) || !empty($jobDateEnd) && !validateDate($jobDateEnd)) {
      // Show the form
      $displayContent = $displayForm;
   // Validate data dates
   } else if ($jobTimeIn>$jobTimeOut) {
      // Show the form
      $displayContent = $displayForm;
   // Validate bonus values
   } else if (!empty($jobBonusId) && is_array($jobBonusId)) {
      // At least one jobBonusId checkbox was checked
      // Make sure its child input is not empty

      ... HERE'S WHERE I'M STUCK ...

   } else {
      // Everything looks good
      // Add record to database
   }
}

Any ideas how to accomplish it?

Thank you much!

Upvotes: 1

Views: 74

Answers (1)

Vasyl Zhuryk
Vasyl Zhuryk

Reputation: 1248

You can use array key, and check child by jobBonusId key:

foreach ($jobBonusId as $key => $bonusId) {
    if (!empty($bonusId)) {
        if (!empty($jobBonusAmount[$key])) { // check a child
            // if child is filled
        } else {
            // not filled
        }
    }
}

It means, that $jobBonusId array is the same to $jobBonusAmount array

Upvotes: 1

Related Questions