laravel 驗證器使用
阿新 • • 發佈:2020-07-13
1.前後端不分離 (form表單提交)
控制器定義驗證規則
<?php namespace App\Http\Controllers\Admin; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; class LoginController { /** * @param Request $request * 登入 */ public function login(Request $request) { $post['name'] = $request->input('name'); $post['password'] = $request->input('password'); $messages = [ 'name.required' => '請輸入賬號', 'name.max' => '賬號錯誤', 'password.required' => '請輸入密碼', 'password.max' => '密碼錯誤', ]; Validator::make($post, [ 'name' => 'required|max:20', 'password' => 'required|max:30', ],$messages)->validate(); } }
前端
@error('name') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror
2.前後端分離
<?php namespace App\Http\Controllers\Admin; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; class LoginController { /** * @param Request $request * 登入 */ public function login(Request $request) { $post['name'] = $request->input('name'); $post['password'] = $request->input('password'); $messages = [ 'name.required' => '請輸入賬號', 'name.max' => '賬號錯誤', 'password.required' => '請輸入密碼', 'password.max' => '密碼錯誤', ]; $validator = Validator::make($post, [ 'name' => 'required|max:20', 'password' => 'required|max:30', ],$messages); if ($validator->fails()){ //返回錯誤資訊 //{ // "name": [ // "賬號錯誤" // ], // "password": [ // "密碼錯誤" // ] //} return $validator->errors(); } } }