2014-04-16 172 views
11

我面临着laravel定制验证消息的问题,这里是我有:Laravel验证自定义消息

$rules = [ 
    'first_name'   => 'required|alpha|min:2', 
    'last_name'    => 'required|alpha|min:2', 
    'email'     => 'required|email|unique:users,email,' . Input::get('id') . ',id', 
    'password'    => 'alpha_num|between:6,12|confirmed', 
    'password_confirmation' => 'alpha_num|between:6,12', 
    'address'    => 'regex:/^[a-z0-9- ]+$/i|min:2', 
    'city'     => 'alpha|min:2', 
    'state'     => 'alpha|min:2|max:2', 
    'zip'     => 'numeric|min:5|max:5', 
    'phone'     => 'regex:/^\d{3}\-\d{3}\-\d{4}$/', 
]; 
$messages = [ 
    'unique' => 'The :attribute already been registered.', 
    'regex' => 'The :attribute number has to be formated : xxx-xxx-xxxx.', 
]; 

现在,如果没有与地址或者因为两个电话号码的问题有正则表达式验证规则,错误消息将是:属性编号必须格式化:xxx-xxx-xxxx,我怎样才能为每个不同的自定义消息?

+0

可能重复[如何Laravel扩展验证类时指定默认的错误消息4](http://stackoverflow.com/questions/17647044/how-to-specify-the-default-error-message-when-extending-the-validation-class-in) –

+0

其实我现在就解决了它: )所有你需要的是这个 – user3150060

+0

如果你解决了这个问题,请回答你的问题,以使未来的SO用户受益。 –

回答

17

这里是这样做,只是而是采用“正则表达式”的方式,使用“phone.regex”

$rules = [ 
    'first_name'   => 'required|alpha|min:2', 
    'last_name'    => 'required|alpha|min:2', 
    'email'     => 'required|email|unique:users,email,' . Input::get('id') . ',id', 
    'password'    => 'alpha_num|between:6,12|confirmed', 
    'password_confirmation' => 'alpha_num|between:6,12', 
    'address'    => 'regex:/^[a-z0-9- ]+$/i|min:2', 
    'city'     => 'alpha|min:2', 
    'state'     => 'alpha|min:2|max:2', 
    'zip'     => 'numeric|min:5|max:5', 
    'phone'     => 'regex:/^\d{3}\-\d{3}\-\d{4}$/', 
]; 
$messages = [ 
    'unique'  => 'The :attribute already been registered.', 
    'phone.regex' => 'The :attribute number is invalid , accepted format: xxx-xxx-xxxx', 
    'address.regex' => 'The :attribute format is invalid.', 
]; 
+1

直到今天才知道:)我也删除了一个额外的数组关闭 - 语法错误:) –