Laravel 4自定义验证规则-在哪里扩展验证器? [英] Laravel 4 custom validation rule - where to extend the validator?
问题描述
我想制定一个自定义验证规则. 目前,我的模型是这样的:
I want to make a custom validation rule. My model looks like this at the moment:
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. 为此,我创建了一个简单的函数
But where I have to put the custom validation rule? I have read that I need to extend it Validator. For this I've created a simple function
Validator::extend('foo', function($attribute, $value, $parameters)
{
return $value == 'foo';
});
我不知道该在哪里检查?
And I don't know where I have to check it?
也许有人可以帮助我.
谢谢
推荐答案
我是通过在/app中创建一个验证文件夹并在其中创建任何自定义验证文件来实现的.
我可以通过编辑 app/start/global.php 自动加载.
I do it by creating a validation folder in /app with any custom validation files in there.
I autoload this by editing 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',
));
我还在此文件中注册了解析器;
I also register the resolver in this file;
Validator::resolver(function($translator, $data, $rules, $messages) {
return new CoreValidator($translator, $data, $rules, $messages);
});
一个示例自定义验证器类(在验证文件夹中);
A sample custom validator class (in the validation folder);
<?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
And add the custom error message to the array in in app/lang/en/validation.php
return array(
...
"postcode" => "Invalid :attribute entered.",
...
)
这篇关于Laravel 4自定义验证规则-在哪里扩展验证器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!