CakePHP - 基于数据库字段添加表单验证

时间:2014-07-22 06:40:02

标签: regex forms validation cakephp-2.0

我需要验证发货时输入的运输信息。 (我正在使用Cake做噩梦!)

每家运输公司的跟踪参考格式都不同。我写了一些正则表达式进行验证,这些正则表达式存储在我的数据库中。

CakePHP的所有验证都发生在模型中,因此我无法使用$this来检索正确的正则表达式。

正则表达式在视图中可用;无论如何在提交表单之前使用它来验证?

我目前正在通过ajax调用发送数据

控制器

    public function editTracking() {
    $this->autoRender = false;

    if ($this->request->is('ajax')) {
        if($this->GoodsOutNote->save($this->request->data['GoodsOutNote'])){
            $this->GoodsOutNote->save($this->request->data['GoodsOutNote']);
            print_r($this->request->data['GoodsOutNote']['tracking_details']);
        }else{
            print_r($errors = $this->GoodsOutNote->validationErrors);
        }

    }
}

查看

<?php echo $this->Form->create('GoodsOutNote',array(
'action'=>'editTracking','default' => false)); ?>
<fieldset>
<?php
    echo $this->Form->input('id',array(
        'default'=>$goodsOutNote['GoodsOutNote']['id']));

    echo $this->Form->input('tracking_details',array(
        'default'=>$goodsOutNote['GoodsOutNote']['tracking_details']));
?>
</fieldset>
<?php echo $this->Form->end(__('Submit'));

$data = $this->Js->get('#GoodsOutNoteEditTrackingForm')->serializeForm(array(
'isForm' => true, 'inline' => true));

$this->Js->get('#GoodsOutNoteEditTrackingForm')->event('submit',
$this->Js->request(
array('action' => 'editTracking', 'controller' => 'goods_out_notes'),
    array(
        'update' => '#tracking_details,#GoodsOutNoteTrackingDetails',
        'data' => $data,
        'async' => true,    
        'dataExpression'=>true,
        'method' => 'PUT'
    )
  )
);
 echo $this->Js->writeBuffer(); 
?>

在视图中,我可以使用$goodsOutNote['ShippingMethod']['valid_regex']来访问正确的格式,但我对如何将其传递给表单感到很遗憾。

1 个答案:

答案 0 :(得分:0)

我已使用以下方法解决了这个问题。

在我的控制器中,我检索了我即将编辑的完整记录。然后我可以使用preg_match()验证输入。我真的很感激任何评论 - 有更好的方法吗?

public function editTracking() {
    $this->autoRender = false;

    if ($this->request->is('ajax')) {

        $id = $this->request->data['GoodsOutNote']['id'];
        $options = array('conditions' => array('GoodsOutNote.' . $this->GoodsOutNote->primaryKey => $id));
        $goodsOutNote = $this->GoodsOutNote->find('first', $options);

        $trackingRef = $this->request->data['GoodsOutNote']['tracking_details'];
        $regex = "/".$goodsOutNote['ShippingMethod']['valid_regex']."/";

        if(preg_match($trackingRef,$regex)){
            if($this->GoodsOutNote->save($this->request->data['GoodsOutNote'])){
                $this->GoodsOutNote->save($this->request->data['GoodsOutNote']);
            print_r($trackingRef);
            }
            else{
            print_r($errors = $this->GoodsOutNote->validationErrors);
            }
        }
        else {
            print_r($errors = $trackingRef.'is not valid');
        }

    }
}