duande3134 2013-05-02 16:52
浏览 8
已采纳

使用for循环在PHP中进行空白空间验证

as you can see, I have a simple registration form, and a PHP script just to validate some fields. The idea here is, that if you have 20+ fields, and you required at-least the user to fill .. username, lastname and age, then you would store it in an array like I have done below.

$needed = array("username", "lastname", "age"); So, as you can see in the code, I do a for loop to check if one of them is filled, now the code works for the most part. for ex: if you don't fill the three fields it will say

You must fill username to continue

You must fill lastname to continue

You must fill age to continue

But, if You fill on field and left the other two, or fill two and then leave one, it will just echo '<p>Required fileds are filled</p>';

So, the problem here is that, all fields should be filled before the script can go to saying echo '<p>Required fileds are filled</p>';

<pre>
<form action='' method='POST'>
    <input type='text' name='username' />
    <input type='text' name='lastname' />
    <input type='text' name='age' />
    <input type='text' name='gender' />
    <input type='text' name='country' />
    <input type='submit' name='reqirester' />
</form>


<?php 

    $needed = array("username", "lastname", "age");

  if($_POST):
    $check = NULL;
for($i=0; $i < count($needed); $i++){

        if($_POST[$needed[$i]] == ''){
          echo '<p>You must fill '.$needed[$i].' to continue<p/>';
        break;  

        }else {
            echo '<p>Required fileds are filled</p>';
        }
    }
 endif;
  • 写回答

2条回答 默认 最新

  • doulu4316 2013-05-02 17:00
    关注

    Why not:

    $required = array("username", "lastname", "age");
    $missing = array_keys(array_diff_key(array_flip($required), array_filter($_POST)));
    
    if($missing)
      printf('You missed: %s', implode(', ', $missing));
    

    or using your output:

    foreach($missing as $key)
      printf('<p>You must fill %s to continue</p>', $key);
    
    if(!$missing)
      print '<p>Required fileds are filled</p>';
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度