简体   繁体   中英

How to make one field required only if another field is used

I have a form where users can enter the names and emails addresses of colleagues. They are not required to enter anything. However if a name is entered then the email address is required.

 <form>
      1st name  <input type="text" name="name_1" value"" />
      1st email <input type="text" name="email_1" value"" />
      2nd name  <input type="text" name="name_2" value""/>
      2nd email  <input type="text" name="email_2" value""/> 
  </form>

I can already make certain fields required using the function below. I think I could use an if else statement to check if the 1st name had a value then make the 1st email required. However the form has twenty potential name / email pairs.

What i'm after is advice about the sort of thing I should be trying to do this rather than a complete solution. I appriciate this a bit of a vague question but I'm very new to PHP and am having difficulty searching for a solution.

function check_required_fields($required_array) {
    $field_errors = array();
    foreach($required_array as $fieldname) {
            if (!isset($_POST[$fieldname]) || (empty($_POST[$fieldname]) && !is_numeric($_POST[$fieldname]))) { 
                    $field_errors[] = $fieldname; 
            }
    }
    return $field_errors;
}

As long as you are consistent with naming your fields like name_1 , you can extract the number from the array keys with substring operations after _ and look for a comparable value in email_ .

foreach ($_POST as $key => $value) {
  // If it is a name field and isn't empty
  if (strpos($key, 'name_') === 0 && !empty($_POST[$key])) {
    // The email field is email_ and the number (which comes after the 5th character in name_num)
    $namenumber = substr($key, 5);
    $emailfield = 'email_' . $namenumber;
    // Append the email requirement onto $field_errors if it's empty in $_POST
    if (empty($_POST[$emailfield])) {
       $field_errors[] = $emailfield;
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM