dougui1977 2015-08-11 21:28
浏览 52
已采纳

通知用户他们错过了表单中的特定输入字段

I am trying to create a form where if a user doesn't enter information into a specific input then on submission of the form, the user is alerted to fill in that input field only (e.g. "Please enter a username").

Currently I have a foreach loop that loops through each input field of the form and assigns a variable with the same name as the field (i.e. $name = $_POST['name']).

What would I implement in my code so I could check each individual input field is empty or not and tell the user this, but keep the code to a bare minimal?

foreach ($_POST as $key => $value) {

     $$key = $_POST[$key];  //assigns variable to input.

    }

if(!empty($$key)) {

//code if all fields are not empty  

}
else {

    echo "Please fill in all fields";

}
  • 写回答

1条回答 默认 最新

  • dpjpo746884 2015-08-11 21:38
    关注

    While I do not agree with how you are doing this, a solution would be to add an error array to your first foreach loop.

    foreach ($_POST as $key => $value) {
         ${$key} = $_POST[$key];
    
         // If the field is empty, set an error
         if( empty($value) ) {
             $errors[] = 'Please enter a ' . $key . '.';
         }
    }
    

    And then change the bottom to check for the error array. If it's empty, run your code to complete the form submission. If not, loop through the errors.

    if( empty($errors) ) {
        //code if all fields are not empty
    }
    else {
        // Loop through each error found
        foreach($errors as $error) {
            echo $error;
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路