表单,用于验证上载的XML文件的内容



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

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

标签:预验证,后验证

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

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

我更喜欢自定义验证器,因为如果必须在其他地方重用表单,就不必重新实现检查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,它应该是好的。

最新更新