Zend_Form:如何检查2个字段是否相同

时间:2021-06-07 05:02:03

I have created a form to add a user to a database and make user available for login.

我创建了一个表单来将用户添加到数据库并使用户可以登录。

Now I have two password fields (the second is for validation of the first). How can I add a validator for this kind of validation to zend_form?

现在我有两个密码字段(第二个用于验证第一个)。如何为zend_form添加验证器以进行此类验证?

This is my code for the two password fields:

这是我的两个密码字段的代码:

    $password = new Zend_Form_Element_Password('password', array(
        'validators'=> array(
            'Alnum',
            array('StringLength', array(6,20))
            ),
        'filters'   => array('StringTrim'),
        'label'     => 'Wachtwoord:'
        ));

    $password->addFilter(new Ivo_Filters_Sha1Filter());

    $password2 = new Zend_Form_Element_Password('password', array(
        'validators'=> array(
            'Alnum',
            array('StringLength', array(6,20))
            ),
        'filters'   => array('StringTrim'),
        'required'  => true,
        'label'     => 'Wachtwoord:'
        ));
    $password2->addFilter(new Ivo_Filters_Sha1Filter());

4 个解决方案

#1


3  

When I was looking for the same, I found this very well working generic Validator for Identical Fields. I don't find it now so I just post the code...

当我寻找相同的东西时,我发现这个非常好用于相同字段的通用验证器。我现在没有找到它所以我只是发布代码...

<?php

class Zend_Validate_IdenticalField extends Zend_Validate_Abstract {
  const NOT_MATCH = 'notMatch';
  const MISSING_FIELD_NAME = 'missingFieldName';
  const INVALID_FIELD_NAME = 'invalidFieldName';

  /**
   * @var array
  */
  protected $_messageTemplates = array(
    self::MISSING_FIELD_NAME  =>
      'DEVELOPMENT ERROR: Field name to match against was not provided.',
    self::INVALID_FIELD_NAME  =>
      'DEVELOPMENT ERROR: The field "%fieldName%" was not provided to match against.',
    self::NOT_MATCH =>
      'Does not match %fieldTitle%.'
  );

  /**
   * @var array
  */
  protected $_messageVariables = array(
    'fieldName' => '_fieldName',
    'fieldTitle' => '_fieldTitle'
  );

  /**
   * Name of the field as it appear in the $context array.
   *
   * @var string
   */
  protected $_fieldName;

  /**
   * Title of the field to display in an error message.
   *
   * If evaluates to false then will be set to $this->_fieldName.
   *
   * @var string
  */
  protected $_fieldTitle;

  /**
   * Sets validator options
   *
   * @param  string $fieldName
   * @param  string $fieldTitle
   * @return void
  */
  public function __construct($fieldName, $fieldTitle = null) {
    $this->setFieldName($fieldName);
    $this->setFieldTitle($fieldTitle);
  }

  /**
   * Returns the field name.
   *
   * @return string
  */
  public function getFieldName() {
    return $this->_fieldName;
  }

  /**
   * Sets the field name.
   *
   * @param  string $fieldName
   * @return Zend_Validate_IdenticalField Provides a fluent interface
  */
  public function setFieldName($fieldName) {
    $this->_fieldName = $fieldName;
    return $this;
  }

  /**
   * Returns the field title.
   *
   * @return integer
  */
  public function getFieldTitle() {
    return $this->_fieldTitle;
  }

  /**
   * Sets the field title.
   *
   * @param  string:null $fieldTitle
   * @return Zend_Validate_IdenticalField Provides a fluent interface
  */
  public function setFieldTitle($fieldTitle = null) {
    $this->_fieldTitle = $fieldTitle ? $fieldTitle : $this->_fieldName;
    return $this;
  }

  /**
   * Defined by Zend_Validate_Interface
   *
   * Returns true if and only if a field name has been set, the field name is available in the
   * context, and the value of that field name matches the provided value.
   *
   * @param  string $value
   *
   * @return boolean 
  */ 
  public function isValid($value, $context = null) {
    $this->_setValue($value);
    $field = $this->getFieldName();

    if (empty($field)) {
      $this->_error(self::MISSING_FIELD_NAME);
      return false;
    } elseif (!isset($context[$field])) {
      $this->_error(self::INVALID_FIELD_NAME);
      return false;
    } elseif (is_array($context)) {
      if ($value == $context[$field]) {
        return true;
      }
    } elseif (is_string($context) && ($value == $context)) {
      return true;
    }
    $this->_error(self::NOT_MATCH);
    return false;
  }
}
?>

#2


40  

The current version of Zend_Validate has this built in - while there are plenty of other answers, it seems that all require passing a value to Zend_Validate_Identical. While that may have been needed at one point, you can now pass the name of another element.

当前版本的Zend_Validate内置了这个 - 虽然还有很多其他答案,但似乎都要求将值传递给Zend_Validate_Identical。虽然可能在某一点上需要,但您现在可以传递另一个元素的名称。

From the Zend_Validate section of the reference guide:

从参考指南的Zend_Validate部分:

Zend_Validate_Identical supports also the comparison of form elements. This can be done by using the element's name as token. See the following example:

Zend_Validate_Identical还支持表单元素的比较。这可以通过使用元素的名称作为标记来完成。请参阅以下示例:

$form->addElement('password', 'elementOne');
$form->addElement('password', 'elementTwo', array(
    'validators' => array(
        array('identical', false, array('token' => 'elementOne'))
    )
));

By using the elements name from the first element as token for the second element, the validator validates if the second element is equal with the first element. In the case your user does not enter two identical values, you will get an validation error.

通过使用第一个元素中的元素名称作为第二个元素的标记,验证器验证第二个元素是否与第一个元素相等。如果您的用户没有输入两个相同的值,您将收到验证错误。

#3


1  

here is how i done this :)

这是我如何做到这一点:)

create first pass input then crate second pass input and add Identical validator with data from previous password input.

创建第一个传递输入,然后创建第二个传递输入,并使用来自先前密码输入的数据添加相同的验证器。

$password_2->addValidator('identical', false, $this->_request->getPost('password'));

#4


0  

You can access all form fields from validator, also you can use constructor to pass additional arguments

您可以从验证器访问所有表单域,也可以使用构造函数传递其他参数

class Example_Validator extends Zend_Validate_Abstract{

const NOT_IDENTICALL = 'not same';

private $testValue;    

public function __construct( $arg ) {
      $this->testValue = $arg;    
   }

protected $_messageTemplates = array(
    self::NOT_IDENTICALL => "Passwords aren't same"
);    

public function isValid( $value, $context = null )
{
    echo  $context['password']; 
    echo '<br>';
    echo $this->testValue;

    return true;
}
}

to call this validator

调用此验证器

$form = new Zend_Form();
$form->setAction('success');
$form->setMethod('post');   
$form->addElement('text', 'username');
$usernameElement = $form->getElement('username');
$form->addElement('password', 'password');
$passwordElement = $form->getElement('password');
$myValidator2 = new Example_Validator("Hello !");   
$passwordElement->addValidator($myValidator2, true);    
$form->addElement('submit', 'submit');  
$submitButton = $form->getElement('submit');

#1


3  

When I was looking for the same, I found this very well working generic Validator for Identical Fields. I don't find it now so I just post the code...

当我寻找相同的东西时,我发现这个非常好用于相同字段的通用验证器。我现在没有找到它所以我只是发布代码...

<?php

class Zend_Validate_IdenticalField extends Zend_Validate_Abstract {
  const NOT_MATCH = 'notMatch';
  const MISSING_FIELD_NAME = 'missingFieldName';
  const INVALID_FIELD_NAME = 'invalidFieldName';

  /**
   * @var array
  */
  protected $_messageTemplates = array(
    self::MISSING_FIELD_NAME  =>
      'DEVELOPMENT ERROR: Field name to match against was not provided.',
    self::INVALID_FIELD_NAME  =>
      'DEVELOPMENT ERROR: The field "%fieldName%" was not provided to match against.',
    self::NOT_MATCH =>
      'Does not match %fieldTitle%.'
  );

  /**
   * @var array
  */
  protected $_messageVariables = array(
    'fieldName' => '_fieldName',
    'fieldTitle' => '_fieldTitle'
  );

  /**
   * Name of the field as it appear in the $context array.
   *
   * @var string
   */
  protected $_fieldName;

  /**
   * Title of the field to display in an error message.
   *
   * If evaluates to false then will be set to $this->_fieldName.
   *
   * @var string
  */
  protected $_fieldTitle;

  /**
   * Sets validator options
   *
   * @param  string $fieldName
   * @param  string $fieldTitle
   * @return void
  */
  public function __construct($fieldName, $fieldTitle = null) {
    $this->setFieldName($fieldName);
    $this->setFieldTitle($fieldTitle);
  }

  /**
   * Returns the field name.
   *
   * @return string
  */
  public function getFieldName() {
    return $this->_fieldName;
  }

  /**
   * Sets the field name.
   *
   * @param  string $fieldName
   * @return Zend_Validate_IdenticalField Provides a fluent interface
  */
  public function setFieldName($fieldName) {
    $this->_fieldName = $fieldName;
    return $this;
  }

  /**
   * Returns the field title.
   *
   * @return integer
  */
  public function getFieldTitle() {
    return $this->_fieldTitle;
  }

  /**
   * Sets the field title.
   *
   * @param  string:null $fieldTitle
   * @return Zend_Validate_IdenticalField Provides a fluent interface
  */
  public function setFieldTitle($fieldTitle = null) {
    $this->_fieldTitle = $fieldTitle ? $fieldTitle : $this->_fieldName;
    return $this;
  }

  /**
   * Defined by Zend_Validate_Interface
   *
   * Returns true if and only if a field name has been set, the field name is available in the
   * context, and the value of that field name matches the provided value.
   *
   * @param  string $value
   *
   * @return boolean 
  */ 
  public function isValid($value, $context = null) {
    $this->_setValue($value);
    $field = $this->getFieldName();

    if (empty($field)) {
      $this->_error(self::MISSING_FIELD_NAME);
      return false;
    } elseif (!isset($context[$field])) {
      $this->_error(self::INVALID_FIELD_NAME);
      return false;
    } elseif (is_array($context)) {
      if ($value == $context[$field]) {
        return true;
      }
    } elseif (is_string($context) && ($value == $context)) {
      return true;
    }
    $this->_error(self::NOT_MATCH);
    return false;
  }
}
?>

#2


40  

The current version of Zend_Validate has this built in - while there are plenty of other answers, it seems that all require passing a value to Zend_Validate_Identical. While that may have been needed at one point, you can now pass the name of another element.

当前版本的Zend_Validate内置了这个 - 虽然还有很多其他答案,但似乎都要求将值传递给Zend_Validate_Identical。虽然可能在某一点上需要,但您现在可以传递另一个元素的名称。

From the Zend_Validate section of the reference guide:

从参考指南的Zend_Validate部分:

Zend_Validate_Identical supports also the comparison of form elements. This can be done by using the element's name as token. See the following example:

Zend_Validate_Identical还支持表单元素的比较。这可以通过使用元素的名称作为标记来完成。请参阅以下示例:

$form->addElement('password', 'elementOne');
$form->addElement('password', 'elementTwo', array(
    'validators' => array(
        array('identical', false, array('token' => 'elementOne'))
    )
));

By using the elements name from the first element as token for the second element, the validator validates if the second element is equal with the first element. In the case your user does not enter two identical values, you will get an validation error.

通过使用第一个元素中的元素名称作为第二个元素的标记,验证器验证第二个元素是否与第一个元素相等。如果您的用户没有输入两个相同的值,您将收到验证错误。

#3


1  

here is how i done this :)

这是我如何做到这一点:)

create first pass input then crate second pass input and add Identical validator with data from previous password input.

创建第一个传递输入,然后创建第二个传递输入,并使用来自先前密码输入的数据添加相同的验证器。

$password_2->addValidator('identical', false, $this->_request->getPost('password'));

#4


0  

You can access all form fields from validator, also you can use constructor to pass additional arguments

您可以从验证器访问所有表单域,也可以使用构造函数传递其他参数

class Example_Validator extends Zend_Validate_Abstract{

const NOT_IDENTICALL = 'not same';

private $testValue;    

public function __construct( $arg ) {
      $this->testValue = $arg;    
   }

protected $_messageTemplates = array(
    self::NOT_IDENTICALL => "Passwords aren't same"
);    

public function isValid( $value, $context = null )
{
    echo  $context['password']; 
    echo '<br>';
    echo $this->testValue;

    return true;
}
}

to call this validator

调用此验证器

$form = new Zend_Form();
$form->setAction('success');
$form->setMethod('post');   
$form->addElement('text', 'username');
$usernameElement = $form->getElement('username');
$form->addElement('password', 'password');
$passwordElement = $form->getElement('password');
$myValidator2 = new Example_Validator("Hello !");   
$passwordElement->addValidator($myValidator2, true);    
$form->addElement('submit', 'submit');  
$submitButton = $form->getElement('submit');