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

报告相同问题?