0

我一直对 Yii 中的验证规则感到困惑。我确信当我给出输入时没有错误,符合给定的规则。

这是我的模型中的验证规则:

 
    // public $user_phone; //updated: this isn't necessary
    public $maxId;
    ...
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('user_phone', 'required', 'message'=>'{attribute} cannot be empty.<br />'),
            array('user_phone', 'length', 'max'=>12),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('user_phone', 'safe', 'on'=>'search'),
            );
    } 

这是我在控制器中调用验证函数的时候:更新:添加了模型属性的分配

 
    public function actionOrder(){
        $order = new IptvOrder;
        if(isset($_POST["IptvOrder"])) {
            $order->attributes = $_POST["IptvOrder"]; // this is what I forgot
            // some assignments to $id, $phone, $date, $time
            if($order->validate()) {
                $order->addOrder($id, $phone, $date, $time);
                $this->redirect(array('order/orderConfirm'));
            }
        ...blablabla...
    } 

我将验证错误消息放在视图中:

 
    ...blablabla...
    <?php
        echo $form->label($order,'Phone Number');
        echo "<font color='red'> *</font>";
        echo "<span style='font-size:10pt; color:#888888'><br/>Digunakan untuk konfirmasi pemesanan. Kerahasiaan kami jamin.</span><br/>";
        echo $form->textField($order,'user_phone'); 
        echo "<font color='red'>".$form->error($order, 'user_phone')."</font>";
    ?>
        echo CHtml::submitButton('Pesan Sekarang', array('confirm' => 'Apakah anda yakin?
Silahkan cek pemesanan anda terlebih dahulu.'));
    ...blablabla...
    
// $form is CActiveForm, $order is the model

尽管文本字段不为空,但它不会被重定向到 order/orderConfirm。有人可以帮忙吗?谢谢 :)

4

1 回答 1

0
  1. 转储$order->attributes检查属性user_phone是否有内容或为空
  2. 打印出给定错误的来源$order->getErrors()
  3. 关于最大长度验证,因为您对该字段的输入是电话号码,所以我排除了可能的 ASCII 字母,如下例所示

http://www.yiiframework.com/forum/index.php/topic/16338-validation-problem-with-length-on-textfields/

更新:如果您的模型名称Order作为示例,您应该在执行验证之前看起来像

if(isset($_POST['Order']))
        {
            $order->attributes=$_POST['Order']; //<== Make sure you have set data for your order model before performing a validation
//validate part
...
}
于 2013-08-23T08:14:14.630 回答