dse323222 2012-04-19 00:54
浏览 45

从Symfony自定义验证器抛出全局错误的优雅方法?

I'm using Symfony 1.4 to allow users to import various types of CSV files, and I've decided to consolidate validation and sanitizing of the actual contents of uploaded files into a custom validator - The custom validator would extend sfValidatorFile.

Also, when a file contains errors, I'd like to throw global errors on forms, rather than displaying them as field/local errors - and - have the ability to show many validation errors at the same time for a given import file.

I'm pretty sure I can make this work by using a Post Validator, but this doesn't seem like a great fit for a Post Validator (since I really only need knowledge of one form field in order to perform my custom validation), but more importantly, I'd like something a bit more elegant that packages all of the extra validation work into a single custom file validator.

For example, instead of:

$this->validatorSchema['file'] = new sfValidatorFile( … );
$this->validatorSchema->setPostValidator(new myFancyValidator( … ));

I'd just like to do something like:

$this->validatorSchema['file'] = new myFancyValidator( … );

...and have validation errors encountered inside myFancyValidator added to the form's collection of global errors.

I've tried a few different approaches to push errors onto the form's globalErrors from within my custom validator, but I'm missing something regarding how the various pieces of the validation puzzle fit/scope together. Any thoughts as to how to accomplish this? Dependency injection?

  • 写回答

1条回答 默认 最新

  • doutang1856 2012-05-15 13:34
    关注

    Throw a sfValidatorError object in your custom validator, e.g. :

    if(!$isValid){
        // throw global error
        throw new sfValidatorError($this, "invalid");
    }
    else {
        return true;
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大