始终无法在Yii中验证

时间:2013-08-23 07:57:09

标签: php validation yii

我对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。有人可以帮忙吗?谢谢:))

1 个答案:

答案 0 :(得分:0)

  1. 转储$order->attributes检查属性user_phone是否有内容或为空
  2. $order->getErrors()
  3. 打印出您的错误
  4. 关于最大长度验证,因为您对该字段的输入是电话号码,我排除了可能的ASCII字母,如下面的情况
  5. 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
    ...
    }