2016-07-27 81 views
3

我有一個註冊系統,我需要顯示出現的任何驗證錯誤。我的大多數驗證都是通過JavaScript進行檢查的,因爲我使用的是Semantic-UI框架。但有2個自定義驗證規則,我不能真正顯示在JavaScript中,所以我需要查看這兩個錯誤消息中的哪一個,並刷新正確的錯誤消息。循環驗證錯誤,並顯示正確的一個 - Laravel 5.2

這是我與驗證註冊功能:

public function postRegister (Request $request) { 

     $validator = Validator::make($request->all(), [ 
      'username' => 'unique:users', 
      'email' => 'unique:users', 
      'password' => '', 
     ]); 

     if ($validator->fails()) { 
      flash()->error('Error', 'Either your username or email is already take. Please choose a different one.'); 
      return back(); 
     } 

     // Create the user in the Database. 
     User::create([ 
      'email' => $request->input('email'), 
      'username' => $request->input('username'), 
      'password' => bcrypt($request->input('password')), 
      'verified' => 0, 
     ]); 

     // Flash a info message saying you need to confirm your email. 
     flash()->overlay('Info', 'You have successfully registered. Please confirm your email address in your inbox.'); 

     return redirect()->back(); 

正如你可以看到有兩個自定義錯誤消息,並且如果用戶得到只是其中的一個錯誤,它會閃爍我的甜警報模式與那個消息。

我怎麼可能通過我的錯誤消息循環,看看哪一個我得到錯誤,並顯示一個特定的Flash消息,該錯誤?

+0

你可以簡單地解析用$ validator->消息() –

回答

2

檢索所有驗證錯誤的數組,你可以使用errors方法:

$messages = $validator->errors(); 
//Determining If Messages Exist For A Field 
if ($messages->has('username')) { 
    //Show custom message 
} 
if ($messages->has('email')) { 
    //Show custom message 
} 
+0

感謝。這樣可行。 – David

+0

不客氣。 –