出于某种原因,我的表单中的字段未被验证。也许有人可以指出我的代码中的任何错误或缺失的项目。我试图按照这里的例子:http://www.symfony-project.org/cookbook/1_2/en/conditional-validator如何在symfony 1.4中正确设置条件验证器?
任何帮助表示赞赏!
我有以下窗体类:
<?php
/**
* dnc_btns form.
*
* @package NMPlus
* @subpackage form
* @author Your name here
* @version SVN: $Id: sfDoctrineFormTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
*/
class dnc_btnsForm extends Basednc_btnsForm
{
public function configure()
{
$this->useFields(array('btn', 'btn_low', 'btn_high', 'company', 'source'));
$this->setValidator('company', new sfValidatorPass());
$this->setValidator('source', new sfValidatorPass());
$this->validatorSchema->setPostValidator(
new sfValidatorCallback(array('callback' => array($this, 'checkBtnType')))
);
}
public function checkBtnType($validator, $values)
{
if (!empty($values['btn']))
{
$this->setValidator('btn', new sfValidatorBtn());
$this->setValidator('btn_low', new sfValidatorPass());
$this->setValidator('btn_high', new sfValidatorPass());
}
if(empty($values['btn']))
{
$this->setValidator('btn_low', new sfValidatorBtn());
$this->setValidator('btn_high', new sfValidatorBtn());
$this->mergePostValidator(
new sfValidatorSchemaCompare('btn_low', sfValidatorSchemaCompare::LESS_THAN, 'btn_high', array(),
array('invalid' => 'The first BTN must be lower than the second.')));
}
return $values;
}
}
这里是我的自定义的验证:
<?php
class sfValidatorBtn extends sfValidatorAnd
{
public function __construct()
{
parent::__construct();
$this->setValidators();
}
public function setValidators()
{
//Btn should be required, not trimmed, and min and max length set.
$this->addValidator(
new sfValidatorString(
array(
'required' => true,
'trim' => false,
'min_length' => 10,
'max_length' => 10,
),
array(
'invalid' => 'BTN must be 10 digits.'
)
)
);
// Adapted from http://stackoverflow.com/questions/1964399/validation-for-a-10-digit-phone-number
$this->addValidator(
new sfValidatorRegex(
array('pattern' => '/^([1-9]\d*)/'),
array('invalid' => 'BTN may not start with a 0.')
)
);
//Checking for existance of given btn in database
$this->addValidator(
new sfValidatorDoctrineUnique(
array('model' => 'dnc_btns', 'column' => 'btn'),
array('invalid' => 'This BTN is already in the database.')
)
);
}
}
我以本教程为起点。我偏离了它,以适应我的目的。如果checkBtnType()方法应该执行验证,那么让代码的那部分位于自定义验证器中会更好吗?还有一种方法来实现现有的验证器,所以我没有重写它们?感谢您的反馈。 – 2011-01-19 15:40:02