2017-03-15 33 views
1

我已經創建了一個Yii CActiveForm,其中有一個字段experience。現在我已經在相應的Yii模型中要求experience。 現在想讓它只需要一個特定的條件。如何爲yii CActiveForm字段編寫自定義客戶端驗證?

比方說:

if($entity == 'student') { // make experience required else make experience optional }

現在我可以設置一個場景用於這一目的的服務器端驗證。但我怎麼能讓我的視圖顯示客戶端驗證經驗領域根據我的新情況。

+0

'$ entity'是表單域嗎? –

+0

是........................ – lakshay

回答

0
public function rules() 
{ 
    return array(
     array('experience', 'myRequired'), 
    ); 
} 

public function myRequired($attribute, $params) 
{ 
    if($this->entity == 'student') 
    { 
     $this->addError('Experience cannot be blank.'); 
     return false; 
    } 

    return true; 
} 
+0

我試過這個,但是這個規則只有在所有其他規則都被驗證的情況下才會起作用.... it如果某個字段爲空,則不會發生錯誤 – lakshay

+0

@lakshay啓用ajax驗證 –

+0

已啓用 – lakshay