2014-04-16 169 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

直到今天才知道:)我也刪除了一個額外的數組關閉 - 語法錯誤:) –