将正则表达式验证程序添加到Zend Framework中的表单元素

时间:2011-08-15 17:33:14

标签: regex zend-framework validation

我在zend Framework中创建了一个Form类。

类Application_Form_UserSignup扩展了Zend_Form {

public function init()
{
    // Set the method for the display form to POST
    $this->setMethod('post');

    // Add an Firstname element
    $this->addElement('text', 'firstname', array(
                              'label'      => 'Your first name:',
                              'required'   => true,
                  'validators' => array('regex', false, array(
                'pattern'   => '/[^<>]/i',
                'messages'  =>  'Your first name cannot contain those characters : < >'))
    ));
    }

}

我想使用Zend_Validate_Regex验证器使用我自己的正则表达式对其进行验证。

语法中必定存在错误,因为我收到此错误但我无法弄明白。

错误是:

消息:传递给addValidators()的验证器无效 堆栈跟踪:

  

0 /usr/share/php/libzend-framework-php/Zend/Form/Element.php(1217):Zend_Form_Element-&gt; addValidators(Array)
  1 /usr/share/php/libzend-framework-php/Zend/Form/Element.php(363):Zend_Form_Element-&gt; setValidators(Array)
  2 /usr/share/php/libzend-framework-php/Zend/Form/Element.php(253):Zend_Form_Element-&gt; setOptions(Array)
  3 /usr/share/php/libzend-framework-php/Zend/Form.php(1108):Zend_Form_Element-&gt; __ construct('firstname',Array)
  4 /usr/share/php/libzend-framework-php/Zend/Form.php(1039):Zend_Form-&gt; createElement('text','firstname',Array)
  5 /home/damiens/workspace/manu/application/forms/UserSignup.php(18):Zend_Form-&gt; addElement('text','firstname',Array)
  6 /usr/share/php/libzend-framework-php/Zend/Form.php(240):Application_Form_UserSignup-&gt; init()
  7 /home/damiens/workspace/manu/application/controllers/UsersController.php(35):Zend_Form-&gt; __ construct()
  8 /usr/share/php/libzend-framework-php/Zend/Controller/Action.php(513):UsersController-&gt; signupAction()
  9 /usr/share/php/libzend-framework-php/Zend/Controller/Dispatcher/Standard.php(295):Zend_Controller_Action-&gt; dispatch('signupAction')
  10 /usr/share/php/libzend-framework-php/Zend/Controller/Front.php(954):Zend_Controller_Dispatcher_Standard-&gt; dispatch(Object(Zend_Controller_Request_Http),Object(Zend_Controller_Response_Http))
  11 /usr/share/php/libzend-framework-php/Zend/Application/Bootstrap/Bootstrap.php(97):Zend_Controller_Front-&gt; dispatch()
  12 /usr/share/php/libzend-framework-php/Zend/Application.php(366):Zend_Application_Bootstrap_Bootstrap-&gt; run()
  13 /home/damiens/workspace/manu/public/index.php(26):Zend_Application-&gt; run()
  14 {main}

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:8)

其addValidatorS(多个验证器):

$this->addElement('text', 'firstname', array(
                          'label'      => 'Your first name:',
                          'required'   => true,
              'validators' => array(
                  array('regex', false, array(
                  'pattern'   => '/[^<>]/i',
                  'messages'  =>  'Your first name cannot contain those characters : < >'))
              )
));