在Laravel 4中显示自定义验证的错误消息 [英] Display Error Message for Custom Validation in Laravel 4
问题描述
我通过创建一个类创建了一个自定义错误函数;
I have created a custom error function by creating a class;
<?php
class CoreValidator extends Illuminate\Validation\Validator
{
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;
}
}
我在模型中引用了它;
I reference it in my model;
public static $rules = array(
'first_name' => 'required|Max:45',
'surname' => 'required|Max:45',
'address_line_1' => 'required|Max:255',
'address_line_2' => 'Max:255',
'address_line_3' => 'Max:255',
'town' => 'required|Max:45',
'county' => 'Max:45',
'postcode' => 'required|Postcode',
'phone_number' => 'required|Max:22'
);
它已在我的 global.php 中注册;
Validator::resolver(function($translator, $data, $rules, $messages) {
return new CoreValidator($translator, $data, $rules, $messages);
});
一切正常,但是返回的错误消息是
It all works well, but the error message it returns is
validation.postcode
validation.postcode
如何/在何处为此设置自定义错误消息?
我尝试使用(两者都不起作用)设置 app/lang/zh-CN/validation.php ;
How/where do I set a custom error message for this?
I have tried setting app/lang/en/validation.php with (neither work);
'custom' => array(
"validation.postcode" => "my error message 1",
"postcode" => "my error message 2"
)
P.S.我知道已经有一个正则表达式验证方法,但是这个问题对我来说更通用.
P.S. I know that there is a regex validation method already, but this problem is more generic for me.
推荐答案
我认为我已经破解了.
我将消息添加到了 app/lang/en/validation.php 的主数组中,而不是添加到了自定义子数组中.
I added the message to the main array in app/lang/en/validation.php, not into the custom sub-array.
return array(
...
"url" => "The :attribute format is invalid.",
"postcode" => "my error message 2",
...
)
如果这不是正确的方法,那么有人可以自由地纠正我.
If this isn't the correct way, then someone is free to correct me.
这篇关于在Laravel 4中显示自定义验证的错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!