【问题标题】:Laravel 4 custom validation rule - where to extend the validator?Laravel 4 自定义验证规则 - 在哪里扩展验证器?
【发布时间】:2013-12-11 11:28:34
【问题描述】:

我想制定一个自定义验证规则。 我的模型现在看起来像这样:

protected $rules = array(
    'first_name'  => 'required',
    'last_name'   => 'required',
    'ssn'         => 'required|integer|min:4|max:4',
    'email'       => 'required|email',
    'dob'         => 'required|checkAge',
    'phone'       => 'required',
    'street'      => 'required',
    'postal_code' => 'required|integer|min:4',
    'city'        => 'required'
);

但是我必须把自定义验证规则放在哪里? 我读过我需要扩展它验证器。 为此,我创建了一个简单的函数

Validator::extend('foo', function($attribute, $value, $parameters)
{
    return $value == 'foo';
});

我不知道该去哪里检查?

也许有人可以帮助我。

谢谢

【问题讨论】:

  • 我们应该把它放在 Laravel 5 的什么地方?

标签: laravel laravel-4


【解决方案1】:

我通过在 /app 中创建一个包含任何自定义验证文件的验证文件夹来做到这一点。
我通过编辑 app/start/global.php 来自动加载它。

ClassLoader::addDirectories(array(
    app_path() . '/commands',
    app_path() . '/controllers',
    app_path() . '/models',
    app_path() . '/presenters',
    app_path() . '/validation',
    app_path() . '/database/seeds',
));

我也在这个文件中注册了解析器;

Validator::resolver(function($translator, $data, $rules, $messages) {
        return new CoreValidator($translator, $data, $rules, $messages);
    });

一个示例自定义验证器类(在验证文件夹中);

<?php

class CoreValidator extends Illuminate\Validation\Validator
{

    protected $implicitRules = array('Required', 'RequiredWith', 'RequiredWithout', 'RequiredIf', 'Accepted', 'RequiredWithoutField');

    public function __construct(\Symfony\Component\Translation\TranslatorInterface $translator, $data, $rules, $messages = array())
    {
        parent::__construct($translator, $data, $rules, $messages);
        $this->isImplicit('fail');
    }

    public function validatePostcode($attribute, $value, $parameters = null)
    {
        $regex = "/^((GIR 0AA)|((([A-PR-UWYZ][0-9][0-9]?)|(([A-PR-UWYZ][A-HK-Y][0-9][0-9]?)|(([A-PR-UWYZ][0-9][A-HJKSTUW])|([A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRVWXY])))) [0-9][ABD-HJLNP-UW-Z]{2}))$/i";
        if (preg_match($regex, $value)) {
            return true;
        }
        return false;
    }
}

并将自定义错误消息添加到 app/lang/en/validation.php 中的数组中

return array(
...
"postcode" => "Invalid :attribute entered.",
...
)

【讨论】:

  • 我还创建了一个类似的验证文件夹,我喜欢在其中放置所有验证内容。我喜欢将验证与我的模型分开,因为那感觉很草率
【解决方案2】:

可以在应用程序启动后立即添加扩展。我所做的是在routes.phpfilters.php 的同一级别中创建一个validations.php 文件,然后将其添加到我的app/start/global.php

require app_path().'/filters.php'; /// this one is already there...
require app_path().'/validations.php'; 

【讨论】:

    猜你喜欢
    • 2016-11-22
    • 2013-06-21
    • 2017-04-11
    • 2018-02-18
    • 2018-05-25
    • 2014-04-22
    • 2019-02-12
    • 2017-12-01
    • 2012-03-31
    相关资源
    最近更新 更多