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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?