2013-07-29 88 views
2

我正在使用zend表單並嘗試驗證客戶端驗證。我的代碼是這樣的:zend中驗證表單a的問題

$this->addElement('text', 'email', array(
    'label' => 'Email:', 
    'required' => true, 
    'class' => 'span12', 
    'attribs' => array(
     'required' => true, 
     'pattern'=> "^[A-Za-z0-9._][email protected][A-Za-z0-9.-]+\.[A-Za-z]{2,4}$" 
    ) 
)); 

$this->setAttrib('id', 'lead_form_creation'); 
$this->addElement('text', 'name', array(
    'label' => 'Name:', 
    'required' => true, 
    'class' => 'span12', 
    'attribs' => array(
     'required' => true, 
     'pattern' => '[a-zA-Z]{4,}' 
    ) 

)); 
$this->addElement('text', 'phone', array(
    'label' => 'Phone:', 
    'required' => true, 
    'class' => 'span12', 
    'attribs' => array(
     'required' => true, 
     'pattern' => '\d{4,}' 
     ) 
    )); 

通過以上三個字段,我可以創建一個表單。此外,我的代碼也驗證以上三個領域。但是,無論何時我寫一些有效的電子郵件地址並按Tab鍵,名稱字段和電話號碼字段都會同時顯示爲紅色。但用戶的視角應該只是名字領域。然後,如果名稱不驗證,並按標籤,姓名字段以及電話字段應顯示錯誤。 請讓我知道我在attrbs屬性或其他地方是否需要提及任何內容? 在此先感謝。

回答

0

錯字在你的代碼(attribs應該是屬性):

$this->addElement('text', 'email', array(
    'label' => 'Email:', 
    'required' => true, 
    'class' => 'span12', 
    'attributes' => array(
     'required' => true, 
     'pattern'=> "^[A-Za-z0-9._][email protected][A-Za-z0-9.-]+\.[A-Za-z]{2,4}$" 
    ) 
)); 

$this->setAttrib('id', 'lead_form_creation'); 
$this->addElement('text', 'name', array(
    'label' => 'Name:', 
    'required' => true, 
    'class' => 'span12', 
    'attributes' => array(
     'required' => true, 
     'pattern' => '[a-zA-Z]{4,}' 
    ) 
)); 

$this->addElement('text', 'phone', array(
    'label' => 'Phone:', 
    'required' => true, 
    'class' => 'span12', 
    'attributes' => array(
     'required' => true, 
     'pattern' => '\d{4,}' 
     ) 
)); 
+0

但是,如果我改變attribs到屬性則沒有驗證的。 – Mausumi

+0

您在此處設置的屬性不是真正的表單驗證,而是HTML5元素(http://www.w3schools.com/tags/att_input_pattern.asp),因此請確保您使用的是正確的文檔類型和支持這些屬性的瀏覽器。例如,對於服務器端驗證使用正則表達式(另請參閱http://stackoverflow.com/questions/7068376/add-a-regex-validator-to-a-form-element-in-the-zend-framework) – RMK

+0

如果我使用屬性,那麼它會生成: 此ID僅適用於電子郵件,其他字段也是如此。 – Mausumi