0

我有一个上传 XML 文件的表单。提交表单后,我必须检查 XML 文件中一对标签的内容。如果标签的内容与预期的不同,则应在表单旁边显示错误。

我不知道如何组织这段代码,有什么帮助吗?

标签: 预验证, 后验证

4

1 回答 1

3

您有几个地方可以执行此检查:

  • 在创建表单的操作中
  • 在使用自定义验证器的表单中
  • 在模型类中(真的不推荐......)

我更喜欢自定义验证器,因为如果您必须在其他地方重新使用表单,您将不必重新实现检查 xml 的逻辑。

因此,在您的 sfForm 类中,将自定义验证器添加到您的文件小部件:

class MyForm extends sfForm
{
  public function configure()
  {
    // .. other widget / validator configuration

    $this->validatorSchema['file'] = new customXmlFileValidator(array(
      'required'  => true,
    ));

在您的新验证器内部/lib/validator/customXmlFileValidator.class.php

// you extend sfValidatorFile, so you keep the basic file validator
class customXmlFileValidator extends sfValidatorFile
{
  protected function configure($options = array(), $messages = array())
  {
    parent::configure($options, $messages);

    // define a custom message for the xml validation
    $this->addMessage('xml_invalid', 'The XML is not valid');
  }

  protected function doClean($value)
  {
    // it returns a sfValidatedFile object
    $value = parent::doClean($value);

    // load xml file
    $doc = new DOMDocument();
    $doc->load($this->getTempName());

    // do what ever you want with the dom to validate your xml
    $xpath = new DOMXPath($doc);
    $xpath->query('/my/xpath');

    // if validation failed, throw an error
    if (true !== $result)
    {
      throw new sfValidatorError($this, 'xml_invalid');
    }

    // otherwise return the sfValidatedFile object from the extended class
    return $value;
  }
}

不要忘记清除缓存php symfony cc,应该没问题。

于 2012-10-08T21:29:31.330 回答