doujia7094 2012-03-29 15:29
浏览 5
已采纳

如何仅在使用另一个字段时才需要创建一个字段

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;
}
  • 写回答

1条回答 默认 最新

  • douhui5953 2012-03-29 15:37
    关注

    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;
        }
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入