尽管验证被触发,CakePHP错误消息仍未显示

时间:2013-09-05 23:04:24

标签: php html validation cakephp

也许有一种更简单的方法来验证这不需要自定义方法,但我正在尝试验证输入的值是否是2个尾随零(减去$符号)或百分比的美元金额。 EX:24%或47.00

如果输入了除此之外的其他内容,表单将无法保存,因此我知道它正在运行。但是,未显示错误消息。同样,当输入正确的输入时,表格将保存。

我想要注意一件事,因为我相信有人会提到它。我必须为输入创建一个单独的标签,因为该表已设置为容纳单选按钮。我也试过它,所以输入是通过表单助手(没有标签)生成的,错误信息仍然没有出现。

这是表格(我省略了存款以外的其他单选按钮以保持更短的时间)

<table class = "settings_table">
     <?php echo $this->Form->create('settings'); ?>
    <tr>            
         <td><? echo $this->Form->radio('Require deposit',$options,$deposit_attributes); ?></td>
    </tr>
    <?php
         if($deposit_attributes['value'] == 'enable'){
    ?>
    <tr>
         <td><label>Deposit Amount (% or dollar amount). EX: 25% or 50.00</lablel</td>
         <td><? echo $this->Form->input('deposit_amount', array('label' =>'', 'value' => $settings['Setting']['deposit_amount'])); ?></td>
    </tr>
    <?php
        }
    ?>
    <tr>
        <td></td><td><?php echo $this->Form->end(__('Submit')); ?></td>
    </tr>
</table>

这是我的验证

function confirm_decimal_or_percent($array, $field){
    if(preg_match('/^\d+\.\d+$/',$array['deposit_amount']) AND (strlen($array['deposit_amount']) - strrpos($array['deposit_amount'], '.') - 1) == 2 ) {
        return true;
    }
    if(preg_match('#[\d.]+%#', $array['deposit_amount'])) {
        return true;
    }
}

 public $validate = array(
    'deposit_amount' => array(
        'valid' => array(
            'rule' => array('confirm_decimal_or_percent','deposit_amount'),
            'message' => 'Please enter either a percent or a decimal amount EX: 50% or 20.00'
        )
    )
);

在我的控制器中,我手动构建数组,因为出于某种原因,单选按钮输入与文本输入分开分组。

Array ( 
    [email] => enable         //radio button input
    [check] => enable         //radio button input
    [charge_user] => enable   //radio button input
    [deposit] => enable       //radio button input
    [settings] => Array (     //settings is the name of the form
            [deposit_amount] => 42.00   //this is the deposit amount
             ) 
   )

这是控制器

$email = $this->request->data['email'];
$check = $this->request->data['check'];
$charge_user = $this->request->data['charge_user'];
$deposit = $this->request->data['deposit'];

if(isset($this->request->data['settings']['deposit_amount'])){
    $deposit_amount = $this->request->data['settings']['deposit_amount'];
}
elseif($deposit == "disable"){
    $deposit_amount = NULL;
}

$settings = array('user_id' => $user_id,'email' => $email, 'check' => $check, 'charge_user' => $charge_user, 'deposit' => $deposit, 'deposit_amount' => $deposit_amount);


$this->Setting->set($settings);
if($this->Setting->validates() == true){
    $this->Setting->id = $id;
    $this->Setting->save($this->request->data);
$this->Session->setFlash('Your settings have been updated');
$this->redirect(array('action' => 'index'));
}

我正在使用Cake 2.3.8

1 个答案:

答案 0 :(得分:0)

看一下这个链接,

- 这可能会对你有所帮助。