2010-03-31 50 views
4

我有以下代碼:我如何定製Zend_Form正則表達式錯誤信息?

 $postcode = $form->createElement('text', 'postcode'); 
    $postcode->setLabel('Post code:'); 
    $postcode->addValidator('regex', false, 
     array('/^[a-z]{1,3}[0-9]{1,3} ?[0-9]{1,3}[a-z]{1,3}$/i')); 
    $postcode->addFilters(array('StringToUpper')); 
    $postcode->setRequired(true);

它的形式創建了一個輸入框,並設置正則表達式驗證規則和工作得很好。

的問題是,當用戶輸入了一個無效的郵政編碼它顯示錯誤消息是這樣的:

'POSTCODE' does not match against pattern 
    '/^[a-z]{1,3}[0-9]{1,3} ?[0-9]{1,3}[a-z]{1,3}$/i'

(其中輸入是郵編)

如何更改該消息是一個小更友好?

回答

5

我覺得要記住,你可以在驗證設置的錯誤消息:

$postcode = $form->createElement('text', 'postcode'); 
$postcode->setLabel('Post code:'); 
$postcode->addValidator('regex', false, array(
    'pattern' => '/^[a-z]{1,3}[0-9]{1,3} ?[0-9]{1,3}[a-z]{1,3}$/i') 
    'messages' => array(
     'regexInvalid' => "Invalid type given, value should be string, integer or float", 
     'regexNotMatch' => "'%value%' does not match against pattern '%pattern%'", 
     'regexErrorous' => "There was an internal error while using the pattern '%pattern%'" 
    ) 
); 
$postcode->addFilters(array('StringToUpper')); 
$postcode->setRequired(true); 

如果還是不行,請嘗試

  • setErrorMessages(數組$消息):添加在表單驗證錯誤上顯示多條錯誤消息,覆蓋所有以前設置的錯誤消息。
1

如果你定義驗證外部變量使用setMessage()

$validator = new Zend_Validate_Alnum(); 
$validator->setMessage('My custom error message for given validation rule', 
         Zend_Validate_Alnum::INVALID); 
$formElement->addValidator($validator); 

正如您上面的例子驗證表單中看到不從任何其他種類的Zend_Validate_的*情況有所不同。

設置驗證消息包括查看API Docs並找出給定驗證錯誤的消息常量(正如我在Zend_Validate_Alnum :: INVALID情況下那樣)。當然,如果您的IDE提供了良好的上下文自動完成功能,只需輸入驗證器類就足夠了 - 因爲在大多數情況下,消息常量是非常明顯的。

另一種方法是用Zend_Form的魔術方法,並簡單地通過「信息」鍵,作爲參數傳遞給您的驗證:

$formElement->addValidator(array(
    'alnum', false, array('messages' => array(
    Zend_Validate_Alnum::INVALID => 'my message' 
    )) 
)); 

這將在內部引發Zend_Validate_Abstract來定義的setMessages()方法,並在本質只是爲Zend_Form定義的一個快捷/節省時間的工具。

注意:ZF手冊中有關於驗證消息的dedicated section

0

你可以使用原來的Zend郵政編碼驗證

$user->addElement('text', 'postcode', array('label' => 'Postcode *', 
    'required' => true,   
    'class' => 'postcode_anywhere', 
    "validators" => array(
     array("NotEmpty", false, array("messages" => array("isEmpty" => "Required *"),)), 
     array('PostCode', false, array('locale' => 'en_GB') 
     ) 
    ), 
    'filters' => array(array('StringToUpper')), 
    'class' => 'text' 
     ) 
);