验证具有相同名称的多个字段 [英] Validating multiple fields with the same name

查看:135
本文介绍了验证具有相同名称的多个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个视图文件,如下所示:

I have a view file that looks like this:

<?php
    echo $this->Form->create('ModelName');
        echo $this->Form->input('ModelName.0.firstField');
        echo $this->Form->input('ModelName.0.secondField');
        echo $this->Form->input('ModelName.1.firstField');
        echo $this->Form->input('ModelName.1.secondField');
    echo $this->Form->end();
?>

我的问题是,如何验证此数据?我不保存,所以它似乎毫无意义,我调用save或saveAll方法。

My question is, how do I validate this data? I'm not saving, so it seems pointless to me to call the save or saveAll methods. I just want to validate the data before I process it and display the results to the user.

目前使用的操作:

<?php
    if ($this->request->is('post')) {
        $this->ModelName->set($this->request->data);
        if ($this->ModelName->validates()) {
            echo $this->Session->setFlash('Success');
        } else {
            echo $this->Session->setFlash('Failure');
        }
    }
?>

它是成功的,即使我把数据,肯定会失败。
我也尝试过:

Is it succeeds all the time even when I'm putting in data that should definitely fail. I have also tried:

<?php
    if ($this->request->is('post')) {
        if ($this->ModelName->validateMany($this->request->data)) {
            echo $this->Session->setFlash('Success');
        } else {
            echo $this->Session->setFlash('Failure');
        }
    }
?>

并且所有的时间都返回成功,但这可能是由于我不知道如何正确使用validateMany。

And that return success all the time as well, but that may be due to the fact that I don't know how to properly use validateMany.

推荐答案

Model :: set 用于将单个数据集/记录分配给模型的当前实例。因此,您可能只验证POST数据中的第一组数据。你必须遍历POST数据中的每个记录, Model :: set 它到Model数据,然后调用 Model :: validates

Model::set is used for assigning a single set/record of data to the current instance of the Model. So it may be possible that you are only validating the first set of data in your POST data. You would have to iterate through each record in the POST data, Model::set it to the Model data, and then call Model::validates.

代替上述方法或 Model :: validateMany ,尝试使用 Model :: saveAll 而不实际保存。

Instead of the above method or Model::validateMany, try using Model::saveAll without actually saving.

http://api20.cakephp.org/class/model#method-ModelsaveAll


validate:设置为false以禁用验证,true在保存前验证每个记录,'第一'验证所有记录之前保存(默认),或'仅'验证记录,但不验证保存它们。

validate: Set to false to disable validation, true to validate each record before saving, 'first' to validate all records before any are saved (default), or 'only' to only validate the records, but not save them.



<?php
    if ($this->request->is('post')) {
        if ($this->ModelName->saveAll($this->request->data, array('validate' => 'only'))) {
            echo $this->Session->setFlash('Success');
        } else {
            echo $this->Session->setFlash('Failure');
        }
    }
?>

这篇关于验证具有相同名称的多个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆