dongsou8980 2012-07-30 22:29
浏览 48
已采纳

建议在php中扩展动态表单验证

I have a form which (on a previous page) users can select how many items they want to include. Once the second page is submitted, it is run through a validation script which takes the requirement, the field name, and a message to return if an error occurs in the validation.

if($numFieldSelectedearlier > 0) {
    for($z=1; $z<=$numFieldSelectedearlier; $z++) {
        $rules[] = "required,name,Name for item {$z} is required.";
    }
}

In my html form, the field looks like the following:

<form name="someForm" action="" method="post">

<?php if ($numFieldSelectedearlier > 0) {
    for($y=1; $y <= $numFieldSelectedearlier; $y++) { ?>        
    <input type="text" name="name[]" id="name<?php echo $y; ?>" />
<?php }
} ?>
....

The problem I have is, the script is currently build to handle single elements (one field named "name", etc). The php validator takes all POST elements and breaks them out as fields to do the validation and I'm struggling to figure out how to either modify the validation script itself (which I'm somewhat hesitant to do given it would change the overall structure of the validator to check if the element name was itself an array then loop through) or if I am perhaps not thinking about a simpler way to handle the actual $rules creation piece.

Note: it may seem the only thing I care about is the a field is required but I want to essentially pass the arrayed item through the same validation options as any other field (required, numbers only, email, etc) so I don't want to duplicate code for what in theory already exists.

Thank you for any assistance you can provide.

  • 写回答

1条回答 默认 最新

  • dpvv37755 2012-07-30 22:35
    关注

    Since you're doing a loop already on both sides, why not just use names like name1, name2, etc. and link your rules to those fields?

    On the HTML side, you would change the name:

    <input type="text" name="name<?php echo $y; ?>" ... />
    

    And on the rules creation side, you would bind to those field names:

    if($numFieldSelectedearlier > 0) {
        for($z=1; $z<=$numFieldSelectedearlier; $z++) {
            $rules[] = "required,name{$z},Name for item {$z} is required.";
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?