我有一个更改密码的表单,它检查password
字段中的min_length
和required
。然后将password
字段与confirm
字段进行比较。
如果我在这个表单上发布的字符少于所需的最小字符数(并且密码和确认框匹配),它会在最小长度(这是预期的)和密码不匹配(意外的)方面引发错误。
有人能说出原因吗?
<?php
class ChangeMyPasswordForm extends sfForm {
const PASSWORD_MIN_LENGTH_MSG = "<li>We could not update your password because your password must be at least 8 characters long. Please choose a different password.</li>";
const PASSWORD_MISMATCH_MSG = "<li>We could not update your password because your passwords didn't match. Please try again.</li>";
const PASSWORD_REQUIRED_MSG = "<li>We could not update your password because your password was blank. Please enter a password.</li>";
protected static $labels = array(
'password' => 'Your Password',
'confirm' => 'Re-enter Password',
);
/**
* Called in sfForm's constructor.
*/
public function configure()
{
$this->setWidgets(array(
'password' => new sfWidgetFormInputPassword(array()),
'confirm' => new sfWidgetFormInputPassword(array()),
));
$this->setValidators(array(
'password' => $this->_setPasswordValidator(),
'confirm' => new sfValidatorPass(),
));
$this->mergePostValidator(
new sfValidatorSchemaCompare('password', sfValidatorSchemaCompare::EQUAL,
'confirm', array(), array(
'invalid' => self::PASSWORD_MISMATCH_MSG,
)
)
);
$this->widgetSchema->setLabels(self::$labels);
}
/**
* Returns validators for the password field.
* @return sfValidatorString
*/
private function _setPasswordValidator()
{
$v = new sfValidatorString();
$v->setOption('min_length', 8);
$v->setMessage('min_length', self::PASSWORD_MIN_LENGTH_MSG);
$v->setMessage('required', self::PASSWORD_REQUIRED_MSG);
return $v;
}
}
编辑:这可能有助于=>我抛出错误的视图
<?php if ($form->hasGlobalErrors() || $form->hasErrors()): ?>
<div class="error">
<p class="bottom"><b>Oops!</b></p>
<ul>
<?php foreach ($form->getGlobalErrors() as $name => $error): ?>
<?php echo $error ?>
<?php endforeach; ?>
<?php foreach ($form->getErrorSchema()->getErrors() as $error): ?>
<?php echo $error; ?>
<?php endforeach; ?>
</ul>
</div>
<? endif; ?>
验证过程分为两个阶段:正常验证器和后验证器,第一个预期错误来自验证的正常阶段(每个字段)。另一个意外错误来自后验证器。
当您将表单与请求值绑定时,作为$form->isValidat(),所有验证器都会被处理(正常和后期),因此,如果其中任何一个(或者在本例中两者都有)中存在错误,它们将存储在稍后显示的字段中。
希望这个足够清楚
编辑:对不起,我的英语不太好,我的头脑也不好,所以,这里有一些很有帮助的东西(Symfony Forms in Action-Advanced Validaton)。不管怎样,我第一次读的时候,我没有注意到"两个密码都是mach"的部分,所以我的答案不是那么准确。以下是注册表单的小部件配置示例我有Symfony注册表单小部件配置
终于想通了。看起来sfValidatorSchemaCompare比较了整个小部件、验证器和所有(而不仅仅是它们返回的值)。因此,如果我比较两个小部件,而它们没有相同的验证器(即一个min_length=3,另一个min_length=6),它将失败。