javck
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    --- tags: laravel --- # 表單驗證 ![](https://i.imgur.com/I4N0JIT.jpg) ![](https://i.imgur.com/gaFzFp8.jpg) ![](https://i.imgur.com/gMdRxR8.jpg) ## 簡介 Laravel 提供了幾種不同的方法來驗證傳入應用的資料。最常見的就是為所有進入應用的請求呼叫它的 validate() ,實際上還有更多的作法 預設情況下 Laravel 的父類控制器使用了一個名為 ValidatesRequests 的 trait,它提供了一種方便的方法來使用各種強大的驗證規則以驗證傳入的 HTTP 請求 ## 快速開始 為了解 Laravel 強大的驗證功能,我們先看一個表單驗證並將錯誤展示給用戶的完整範例: ### 定義路由 首先假設我們在 routes/web.php 路由文件中定義了下面路由: ``` use App\Http\Controllers\PostController; Route::get('/post/create', [PostController::class, 'create']); Route::post('/post', [PostController::class, 'store']); ``` GET 路由會顯示一個供用戶創建新部落格文章的表單,而 POST 路由會將新的文章存到資料庫中 ### 建立控制器 接下來,讓我們一起來看看處理這些路由的簡單控制器。我們暫時先不撰寫 store 方法 ``` <?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use Illuminate\Http\Request; class PostController extends Controller { /** * 顯示創建部落格文章的表單 * * @return \Illuminate\View\View */ public function create() { return view('post.create'); } /** * 將新的文章存到資料庫中 * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // Validate and store the blog post... } } ``` ### 寫驗證邏輯 現在我們開始在 store() 中編寫用來驗證新文章的邏輯程式碼。為此我們將使用 Illuminate\Http\Request 類別提供的 validate() 。如果驗證通過,你的程式會繼續正常運行。如果驗證失敗,則會拋出異常,並自動將對應的錯誤回應回傳給用戶。 在傳統 HTTP 請求下,會生成一個轉址到原先表單網址的回應, 而對於 AJAX 請求則會發送 JSON 回應 為了深入理解 validate(),讓我們接着回到 store(): ``` /** * Store a new blog post. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $validated = $request->validate([ 'title' => 'required|unique:posts|max:255', 'body' => 'required', ]); // The blog post is valid... } ``` 如你所見,我們將所需的驗證規則傳入 validate() 。如果驗證失敗,會自動生成一個對應的回應。而如果驗證通過,那控制器程式會繼續正常運行 你也可以把驗證規則寫成陣列而不是單個 | 分隔的字串 ``` $validatedData = $request->validate([ 'title' => ['required', 'unique:posts', 'max:255'], 'body' => ['required'], ]); ``` 你可以使用 validateWithBag() 來驗證請求,並將所有錯誤訊息儲存在一個 命名錯誤包中: ``` $validatedData = $request->validateWithBag('post', [ 'title' => ['required', 'unique:posts', 'max:255'], 'body' => ['required'], ]); ``` ### 遇到第一次錯誤後停止 有時候我們希望某個欄位在第一次驗證失敗後就停止運行驗證規則,只需要將 bail 添加到規則中: ``` $request->validate([ 'title' => 'bail|required|unique:posts|max:255', 'body' => 'required', ]); ``` 在這個例子中,如果 title 欄位沒有通過 unique 規則,那麼就不會繼續驗證 max 規則。規則會按照撰寫的順序來驗證 ### 針對巢狀參數 如果 HTTP 請求包含「巢狀」參數比如陣列。 可以在驗證規則中使用「點」語法來指定這些參數: ``` $request->validate([ 'title' => 'required|unique:posts|max:255', 'author.name' => 'required', 'author.description' => 'required', ]); ``` 假如你的參數名稱包含點,則可以通過使用反斜槓來將點轉義,以防止其被解釋為 「點」 語法: ``` $request->validate([ 'title' => 'required|unique:posts|max:255', 'v1\.0' => 'required', ]); ``` ## 顯示驗證錯誤 那如果傳入的請求參數未通過指定的驗證規則呢?正如前面所提到的,Laravel 會自動將用戶轉址到之前的網址。另外所有的驗證錯誤資料會自動存儲到閃存 session 中 我們沒有必要在 GET 路由中顯式地綁定錯誤資料到視圖中,Laravel 會檢查 session 中的錯誤,如果有錯誤的話,將會自動將其綁定到視圖中。其中的 $errors 變量是 Illuminate\Support\MessageBag 的一個實例。要了解更多關於該物件更多的資料, 請參閱這篇文章 >技巧: > > $errors變數由 web 中介層群組提供的 Illuminate\View\Middleware\ShareErrorsFromSession 中介層綁定到視圖中。當該中介層被應用後, $errors 變量在你的視圖中總是可取用的,因此可以假設 $errors 變量總是被定義了且總是安全可用的 所以在如下的例子中,當表單驗證失敗時,用戶將被轉址到控制器的 create() ,我們可在視圖中顯示錯誤信息: ``` <!-- /resources/views/post/create.blade.php --> <h1>Create Post</h1> @if ($errors->any()) <div class="alert alert-danger"> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif <!-- Create Post Form --> ``` ### 自定義錯誤訊息 Laravel 內建的驗證規則都有其對應的錯誤訊息位於 resources/lang/en/validation.php。在這個檔案中你將能找到每個驗證規則的翻譯內容,你可以根據應用的需要來修改它們 除此之外,你也能夠複製它們到其他語言的本地化資料夾以擴展更多的支援語言,歡迎參考[Localized 本地化](/QTkf293kT424pTFoNJkjZQ) ### XHR & 驗證 在這個例子中,我們使用的是傳統表單請求。然而現在很多的應用收到的會是由JS前端所發送的 XHR 請求。當使用 XHR 請求的 validate() , Laravel 將不會生成轉址回應。相對的它會生成一個 JSON回應並包含所有的驗證錯誤,該回應將帶 422 HTTP 狀態碼 ### @error 標籤 你亦使用 @error Blade標籤方便地檢查指定欄位是否存在驗證錯誤訊息。在 @error 標籤中,你可以輸出 $message 變數以顯示錯誤訊息 ``` <!-- /resources/views/post/create.blade.php --> <label for="title">Post Title</label> <input id="title" type="text" class="@error('title') is-invalid @enderror"> @error('title') <div class="alert alert-danger">{{ $message }}</div> @enderror ``` ## 重新生成表單 當 Laravel 因為驗證錯誤而生成轉址回應將會自動把所有的請求輸入內容閃存到 Session。透過這樣的方式讓你能夠把所有的輸入內容填回該表單,以省去使用者仍需重新填寫表單的困擾 要取得這些閃存的輸入內容,只需要對 Illuminate\Http\Request 實例呼叫 old() ,這個方法將會幫你取出指定欄位的原輸入內容 `$title = $request->old('title');` Laravel 同樣提供一個全域的 old() 幫助函式,假如你想要在 Blade版型去顯示原輸入內容,這是非常好用的。如果指定的欄位原先並沒有輸入任何內容,將回傳 null `<input type="text" name="title" value="{{ old('title') }}">` ## 針對可選欄位 預設情況下在 Laravel 應用 App\Http\Kernel 類別,全域中介層堆疊中包含了 TrimStrings 和 ConvertEmptyStringsToNull 中介層。因此如果不想讓 null 被驗證器視為錯誤的話,需要將「可選」欄位標記為 nullable : ``` $request->validate([ ... 'publish_at' => 'nullable|date', ]); ``` 在上例中,我們指定了 publish_at 欄位可以是空的或者是一個有效的日期格式。如果 nullable 規則沒有被添加到定義中,驗證器會將 null 視為無效的日期格式 ## 表單請求驗證 ### 建立表單請求 面對更複雜的情況,你可以建立一個「表單請求」來應對更複雜的驗證邏輯。表單請求是一個包含了驗證邏輯的自定義請求類別。要建立一個表單請求類別,請使用 make:request Artisan CLI 命令 `php artisan make:request StorePostRequest` 該命令生成的類別將被放置於 app/Http/Requests 資料夾中。如果該資料夾不存在,在運行 make:request 命令後將會創建這個資料夾。該類別將包含兩個方法, authorize() 和 rules() 就如方法名稱所示, authorize() 用來判斷登入使用者是否具有權限來執行該請求的行為,而 rules() 則回傳用來驗證該請求的規則陣列 ``` /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'title' => 'required|unique:posts|max:255', 'body' => 'required', ]; } ``` >技巧: > >您可以透過型別提示向 rules() 傳入所需的任何依賴項。它們將被 Laravel 服務容器自動解析 所以,驗證規則是如何運行的呢?你所需要做的就是在控制器方法中型別提示傳入的請求。就會在呼叫控制器方法之前先驗證傳入的表單請求,這意味着你不需要在控制器中寫任何驗證邏輯,如果驗證失敗的話控制器方法內的程式將不會被執行就跳出: ``` /** * Store a new blog post. * * @param \App\Http\Requests\StorePostRequest $request * @return Illuminate\Http\Response */ public function store(StorePostRequest $request) { // The incoming request is valid... // Retrieve the validated input data... $validated = $request->validated(); } ``` 如果驗證失敗,就會生成一個讓用戶返回到先前網址的轉址回應。這些錯誤也會被閃存到 session 中,以便這些錯誤都可以在頁面中顯示出來。如果傳入的請求是 XHR,會向用戶回傳具有 422 狀態碼和驗證錯誤訊息的 JSON 格式 HTTP 回應 ### 在表單驗證後加入鉤子 如果你想在表單請求驗證「之後」添加鈎子,可以透過 withValidator() 。該方法接收一個完整的驗證器,允許你在驗證結果返回之前呼叫它的任何方法: ``` /** * Configure the validator instance. * * @param \Illuminate\Validation\Validator $validator * @return void */ public function withValidator($validator) { $validator->after(function ($validator) { if ($this->somethingElseIsInvalid()) { $validator->errors()->add('field', 'Something is wrong with this field!'); } }); } ``` ### 驗證表單請求授權 表單請求類別內也包含了 authorize() 。在這個方法中,你可以檢查經過身份驗證的用戶確定其是否具有更新該資源的權限。比方說,你可以判斷用戶是否擁有更新文章評論的權限,一般來說你可以在這個方法內去利用負責授權的 gates 和 policies ``` use App\Models\Comment; /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { $comment = Comment::find($this->route('comment')); return $comment && $this->user()->can('update', $comment); } ``` 由於所有的表單請求都是繼承了 Laravel 中的請求基礎類別,所以我們可以使用 user() 去獲取當前登入的用戶。同時請注意上述例子中對 route() 的呼叫。這個方法允許你在被呼叫的路由上獲取其定義的 URI 路徑參數,比如下面例子中的 {comment} 路徑參數 `Route::post('/comment/{comment}');` 如果 authorize() 回傳 false,則會自動返回一個包含 403 狀態碼的 HTTP 回應,也不會運行控制器的方法 如果你打算在應用的其它部分處理授權邏輯,只需直接從 authorize() 回傳 true ``` /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } ``` > 提示: > > 你可以向 authorize() 傳入所需的任何依賴項。它們會自動被 Laravel 提供的服務容器自動解析 ## 自定義錯誤訊息 你可以通過複寫表單請求的 messages() 來自定義錯誤訊息。此方法應返回欄位/規則對及其對應錯誤訊息的陣列 ``` /** * Get the error messages for the defined validation rules. * * @return array */ public function messages() { return [ 'title.required' => 'A title is required', 'body.required' => 'A message is required', ]; } ``` ### 自定義驗證屬性 如果你希望將驗證消息的 :attribute 部分替換為自定義欄位名稱,比如將"name"改成名字,則可以複寫 attributes() 來指定自定義名稱。此方法應返回欄位 / 名稱對的陣列 /** * Get custom attributes for validator errors. * * @return array */ public function attributes() { return [ 'email' => 'email address', ]; } ## 準備輸入項的驗證 如果你需要在應用驗證規則前清除請求中的任何資料,可以使用 prepareForValidation() : ``` use Illuminate\Support\Str; /** * Prepare the data for validation. * * @return void */ protected function prepareForValidation() { $this->merge([ 'slug' => Str::slug($this->slug), ]); } ``` ## 手動建立驗證 如果您不想使用請求的 validate() ,可以使用 Validator Facade 來手動創建一個驗證器實例。 Validator 中的 make() 將會生成一個新的驗證器實例: ``` <?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; class PostController extends Controller { /** * Store a new blog post. * * @param Request $request * @return Response */ public function store(Request $request) { $validator = Validator::make($request->all(), [ 'title' => 'required|unique:posts|max:255', 'body' => 'required', ]); if ($validator->fails()) { return redirect('post/create') ->withErrors($validator) ->withInput(); } // Store the blog post... } } ``` make() 中的第一個參數是期望被驗證的資料,第二個參數是應用到資料上的驗證規則 如果驗證失敗,你可以使用 withErrors() 將錯誤資料閃存至 session 中。使用該方法時, $errors 會自動與之後的視圖共享,你可以很方便將其顯示給用戶看。withErrors() 接受驗證器實例. 訊息包或是 PHP 陣列 ## 自動轉址 如果您想要在手動創建驗證器實例的同時,使用請求的 validate() 的自動轉址功能,你可以在現有的驗證器實例上呼叫 validate()。如果驗證失敗,用戶將被自動轉址,或在 XHR 請求下,將會返回一個 JSON 回應 ``` Validator::make($request->all(), [ 'title' => 'required|unique:posts|max:255', 'body' => 'required', ])->validate(); ``` 你可以使用 validateWithBag() 以便在驗證錯誤時能夠儲存錯誤訊息 ``` Validator::make($request->all(), [ 'title' => 'required|unique:posts|max:255', 'body' => 'required', ])->validateWithBag('post'); ``` ## 命名錯誤包 如果你的一個頁面中存在多個表單,可以為錯誤的 MessageBag 加以命名,用於取得指定表單的錯誤訊息。只需將名稱作為 withErrors() 的第二個參數傳遞給它 `return redirect('register')->withErrors($validator, 'login');` 你可以通過 $errors 變數的屬性來訪問命名後的 MessageBag 實例: `{{ $errors->login->first('email') }}` ## 自定義錯誤訊息 如有必要,你也能提供驗證器實例使用的自定義錯誤訊息以取代 Laravel 的預設錯誤訊息。有很多的方式來自定義訊息,首先你需要把自定義訊息以第三參數來傳入 Validator::make() ``` $validator = Validator::make($input, $rules, $messages = [ 'required' => 'The :attribute field is required.', ]); ``` 在這個例子中, :attribute 佔位符將被替換為該欄位的名稱。你也能夠在驗證訊息中加入其他的佔位符,例如: ``` $messages = [ 'same' => 'The :attribute and :other must match.', 'size' => 'The :attribute must be exactly :size.', 'between' => 'The :attribute value :input is not between :min - :max.', 'in' => 'The :attribute must be one of the following types: :values', ]; ``` ### 定義指定欄位的訊息 有時你會需要自定義訊息只針對某個特定欄位,你可以透過「點」語法來達成。在驗證規則前面加上點,在點的前面加上欄位名稱 ``` $messages = [ 'email.required' => 'We need to know your email address!', ]; ``` ### 自定義欄位值 多數的 Laravel 內建錯誤訊息包含一個 :attribute 佔位符用來替換成欄位名稱。為了自定義該佔位符要替換的內容,你能夠以第四參數傳入要替換的欄位佔位符到 Validator::make() ``` $validator = Validator::make($input, $rules, $messages, [ 'email' => 'email address', ]); ``` ### 後勾驗證 驗證器允許您在完成驗證操作後執行附加的回呼方法。以便處理下一步的驗證,甚至是往訊息集合中添加更多的錯誤訊息。您可以在驗證器實例上使用 after 方法來實現 ``` $validator = Validator::make(...); $validator->after(function ($validator) { if ($this->somethingElseIsInvalid()) { $validator->errors()->add( 'field', 'Something is wrong with this field!' ); } }); if ($validator->fails()) { // } ``` ## 處理錯誤訊息 當呼叫 Validator 實例的 errors(),它會返回一個 Illuminate\Support\MessageBag 實例,該實例包含了各種可以很方便地處理錯誤訊息的方法,並自動給所有視圖提供 $errors 變數,這個變數也是 MessageBag 類別的一個實例 ### 取得某欄位的第一個錯誤訊息 你可以使用 first() 取得指定欄位的第一個錯誤訊息 ``` $errors = $validator->errors(); echo $errors->first('email'); ``` ### 取得某欄位的所有錯誤訊息 你可以使用 get() 取得指定欄位所有訊息的陣列 ``` foreach ($errors->get('email') as $message) { // } ``` 如果要驗證表單的陣列欄位,可以使用 * 字元來取得每一個陣列元素的所有錯誤訊息 ``` foreach ($errors->get('attachments.*') as $message) { // } ``` ### 取得所有欄位的所有錯誤訊息 你可以使用 all() 獲取所有欄位的所有錯誤訊息的陣列: ``` foreach ($errors->all() as $message) { // } ``` ### 判斷某欄位是否有錯誤訊息 has() 可用於判斷指定欄位是否包含任何錯誤訊息: ``` if ($errors->has('email')) { // } ``` ## 錯誤訊息的本地化 Laravel內建的驗證規則錯誤訊息被放在應用的 resources/lang/en/validation.php 檔案中。透過這個檔案,你將能根據應用的需要修改內建的錯誤訊息 除此之外,你也能夠複製這個檔案到其他的本地化語言資料夾。如需要了解更多的本地化內容,請參考[Localized 本地化](/QTkf293kT424pTFoNJkjZQ) 你也能夠針對指定欄位跟規則來自定義其錯誤訊息,合併到應用的驗證語言檔案內。只需要把你的訊息自定義內容加入應用檔案 resources/lang/xx/validation.php裡的 custom 陣列中 ``` 'custom' => [ 'email' => [ 'required' => 'We need to know your email address!', 'max' => 'Your email address is too long!' ], ], ``` ## 語言檔的指定屬性 多數的 Laravel 內建錯誤訊息包含一個 :attribute 佔位符用來替換成欄位名稱。為了自定義該佔位符要替換的內容,你能夠在 resources/lang/xx/validation.php 語言檔案的 attributes 陣列中去指定要替換的佔位符及其內容 ``` 'attributes' => [ 'email' => 'email address', ], ``` ### 語言檔的指定值 有時你可能需要將錯誤訊息中的 :value 部分替換為自定義的表示形式。例如下方規則中將 cc 指定為 payment_type 的值 ``` Validator::make($request->all(), [ 'credit_card_number' => 'required_if:payment_type,cc' ]); ``` 如果規則驗證失敗,它將生成如下的錯誤訊息 要將 payment type 原先顯示的 cc 替換為自定義的顯示形式,你可以在 validation 語言檔案中定義 values 陣列來實現: ``` 'values' => [ 'payment_type' => [ 'cc' => 'credit card' ], ], ``` 現在如果規則驗證失敗,將生成如下的錯誤訊息 `The credit card number field is required when payment type is credit card.` ## 可用的驗證規則 ### accepted 待驗證欄位必須是 yes , on ,1 或 true 。這在確認「服務條款」是否同意時很有用 ### active_url 根據 PHP 函數 dns_get_record() ,驗證欄位必須具有有效的 A 或 AAAA 記錄。URL 所提供的主機名時在傳遞給 dns_get_record() 前使用 parse_url() 取得的。 ### after:date 待驗證欄位必須是指定的日期之後的值。日期將被傳遞給 PHP 函數 strtotime(): `'start_date' => 'required|date|after:tomorrow'` 你亦可指定另一個要與日期比較的欄位,而不是傳遞要由 strtotime() 處理的日期字串: `'finish_date' => 'required|date|after:start_date'` ### after_or_equal:date 待驗證欄位的值對應的日期必須在指定日期之後或與給定的日期相同。可參閱 after 規則獲取更多訊息。 ### alpha 待驗證欄位只能由字母組成 ### alpha_dash 待驗證欄位可能包含字母、數字,短破折號(-)和下劃線(_) ### alpha_num 待驗證欄位只能由字母和數字組成 ### array 待驗證欄位必須是有效的 PHP 陣列 ### bail 在首次驗證失敗後立即終止驗證 ### before:date 待驗證欄位的值對應的日期必須在指定的日期之前。日期將會傳遞給 PHP 函數 strtotime()。此外,與 after 規則一致,可以將另外一個待驗證的日期欄位作為 date 的值 ### before_or_equal:date 驗證欄位必須是在指定日期之前或與之相同的日期。這個日期值將會被傳遞給 PHP 的 strtotime() 來計算。除此之外,像 after 規則一樣,驗證中另一個日期欄位的名稱可以作為值傳遞給 date ### between:min,max 驗證欄位的大小必須在指定的 min 和 max 之間。字串、數字、陣列和文件的計算方式都使用 size 規則 ### boolean 驗證的欄位必須可以轉換為 Boolean 類型。 可接受的輸入為 true , false , 1 , 0 , "1" 和 "0" ### confirmed 驗證欄位必須具有匹配字串 _confirmation 。例如,驗證欄位為 password ,則輸入中必須存在與之匹配的 password_confirmation 欄位 ### date 根據 PHP strtotime() ,驗證的欄位必須是有效的日期 ### date_equals:date 驗證欄位必須等於指定日期。日期將傳遞到 PHP strtotime() 用以轉換成有效的 DateTime 實例 ### date_format:format 驗證欄位必須匹配指定的日期格式。當驗證某個欄位的時候,你應該只使用 date 或者 date_format 而不是同時使用。此驗證規則支持 PHP 所有的 DateTime 類別 ### different:field 驗證的欄位必須與另一個指定欄位的值不同 ### digits:value 驗證的字段必須為 numeric ,並且必須具有確切的長度 ### digits_between:min,max 驗證中的欄位必須為 numeric,並且長度必須在指定的 min 和 max 之間 ### dimensions 驗證的檔案必須是圖片並且圖片比例必須符合規則的參數 `'avatar' => 'dimensions:min_width=100,min_height=200'` 可用的規則為: min_width, max_width, min_height, max_height, width, height, ratio. ratio 限制應該表示為寬度除以高度。 這可以通過像 3/2 這樣的語句或像 1.5 這樣的 float 來指定 `'avatar' => 'dimensions:ratio=3/2'` 由於此規則需要多個參數,因此你可以 Rule::dimensions() 來建構可讀性高的規則 ``` use Illuminate\Support\Facades\Validator; use Illuminate\Validation\Rule; Validator::make($data, [ 'avatar' => [ 'required', Rule::dimensions()->maxWidth(1000)->maxHeight(500)->ratio(3 / 2), ], ]); ``` ### distinct 當驗證陣列時,指定的欄位不能有任何重複元素 `'foo.*.id' => 'distinct'` 你能夠加入 ignore_case 來輔助驗證,在這情況下大小寫將視為相同 `'foo.*.id' => 'distinct:ignore_case'` ### email 驗證的欄位必須符合 e-mail 地址格式。當前版本,此種驗證規則由 egulias/email-validator 提供支持。預設使用 RFCValidation 驗證樣式,但你也可以使用其他驗證樣式 `'email' => 'email:rfc,dns'` The example above will apply the RFCValidation and DNSCheckValidation validations. Here's a full list of validation styles you can apply: 例子使用 RFCValidation 和 DNSCheckValidation 驗證樣式。所有可用驗證樣式列表 * rfc: RFCValidation * strict: NoRFCWarningsValidation * dns: DNSCheckValidation * spoof: SpoofCheckValidation * filter: FilterEmailValidation > 當前版本 filter 驗證規則使用 PHP 的 filter_var 方法進行驗證,在 5.8 版本之前的 Laravel 。 dns 和 spoof 驗證器需要 PHP 的 intl 擴展。 ### ends_with:foo,bar,... 驗證的欄位必須以指定的值之一做結尾 ### exclude_if:anotherfield,value 如果_anotherfield_欄位等於_value_,驗證下的欄位將被 validate 和 validated 方法回傳的請求資料排除 ### exclude_unless:anotherfield,value 驗證下的欄位將被 validate 和 validated 方法回傳的請求數據排除,除非 anotherfield 的欄位等於 value ### exists:table,column 驗證的欄位必須存在於指定的資料庫表格中 #### 基本用法 `'state' => 'exists:states'` 如果你需要指定 exists 用來查詢的資料庫。你可以通過使用「點」語法將資料庫的名稱添加到表格前面來實現這個目的 #### 指定欄位名稱 你能夠指定表格的欄位名稱用於驗證規則,只需將之放在表格名稱後 `'state' => 'exists:states,abbreviation'` 有時,你可能需要指定資料庫連線以用於某些查詢。用法是在連線名稱之前加上connect作為前綴 `'email' => 'exists:connection.staff,email'` 除了直接指定表格名稱,你也可以使用關聯模型來指定表格名 `'user_id' => 'exists:App\Models\User,id'` 如果要自定義驗證規則執行的查詢,可以使用 Rule 類別來定義規則。在這個例子中,我們使用陣列指定驗證規則,而不是使用 | 字符來分隔它們: ``` use Illuminate\Support\Facades\Validator; use Illuminate\Validation\Rule; Validator::make($data, [ 'email' => [ 'required', Rule::exists('staff')->where(function ($query) { return $query->where('account_id', 1); }), ], ]); ``` ### file 驗證的欄位必須是成功上傳的檔案 ### filled 驗證的欄位在存在時不能為空 ### gt:field 驗證欄位必須大於指定的 _field_。兩個欄位必須是相同的類型。字串、數字、陣列和文件都使用 size 規則進行相同的評估 ### gte:field 驗證欄位必須大於或等於指定的 _field_。兩個欄位必須是相同的類型。字串、數字、陣列和文件都使用 size 規則進行相同的評估 ### image 驗證的檔案必須是圖片 (jpeg, png, bmp, gif, svg, or webp) ### in:foo,bar,... 驗證欄位必須包含在指定的值列表中。由於此規則通常要求你 implode 陣列,因此可以使用 Rule::in 方法流暢地建構規則 ``` use Illuminate\Support\Facades\Validator; use Illuminate\Validation\Rule; Validator::make($data, [ 'zones' => [ 'required', Rule::in(['first-zone', 'second-zone']), ], ]); ``` ### in_array:anotherfield.* 驗證的欄位必須存在於另一個欄位 anotherfield 的值中 ### integer 驗證的欄位必須是整數 > 注意: > > 此種驗證規則不是驗證欄位是 「integer」 類型,僅驗證字符串或數值包含一個「integer」 ### ip 驗證的欄位必須是 IP 地址 ### ipv4 驗證的欄位必須是 IPv4 地址 ### ipv6 驗證的欄位必須是 IPv6 地址 ### json 驗證的欄位必須是有效的 JSON 字串 ### lt:field 驗證的欄位必須小於給定的欄位,這兩個欄位必須是相同的類型。字串、數值、陣列和檔案大小的計算方式與 size 規則進行評估 ### lte:field 驗證的欄位必須小於或等於給定的欄位,這兩個欄位必須是相同的類型。字串、數值、陣列和檔案大小的計算方式與 size 規則進行評估 ### max:value 驗證中的欄位必須小於或等於 value。字串、數字、陣列或是檔案大小的計算方式都用 size 規則 ### mimetypes:text/plain,... 驗證的檔案必須具備與列出的其中一個相匹配的 MIME 類型: `'video' => 'mimetypes:video/avi,video/mpeg,video/quicktime'` 為了確定上傳檔案的 MIME,框架將會讀取檔案,然後自動推測檔案 MIME 類型,這可能與客戶端提供的 MIME 類型不一致 ### mimes:foo,bar,... 驗證的檔案必須具有與列出的其中一個副檔名相對應的 MIME 類型 #### MIME 規則基本用法 'photo' => 'mimes:jpeg,bmp,png' 即使你可能只需要驗證指定副檔名,但此規則實際上會去驗證檔案的 MIME 類型,其通過讀取檔案內容來推測它的 MIME 類型 可以在以下連接中找到完整的 MIME 類型列表及相對應的副檔名:https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types ### min:value 驗證欄位必須具有最小值。 字串. 數值. 陣列. 檔案大小的計算方式都與 size 規則一致 ### multiple_of:value 驗證欄位並須具備多個值 ### not_in:foo,bar,... 驗證欄位不能包含在指定的值的列表中。 使用 Rule::notIn() 可以更流暢的建立這個規則: ``` use Illuminate\Validation\Rule; Validator::make($data, [ 'toppings' => [ 'required', Rule::notIn(['sprinkles', 'cherries']), ], ]); ``` ### not_regex:pattern 驗證欄位必須與指定的正則表達式不匹配 驗證時,這個規則使用 PHP preg_match()。指定的模式應遵循 preg_match() 所需的相同格式,也包括有效的分隔符。 例如: 'email' => 'not_regex:/^.+$/i' > 注意: > 當使用 regex / not_regex 模式時, 可能需要在陣列中指定規則,而不是使用 | 分隔符 ,特別是在正則表達式包含 | 字元 的情況下 ### nullable 驗證欄位可以為 null。這在驗證基本資料類型時特別有用,例如可以包含空值的字串和整數 ### numeric 驗證欄位必須為數值 ### password 驗證欄位必須與當前登入用戶的密碼相同。你可以通過傳入第一個參數來指定身份驗證看守器(Authentication Guard) `'password' => 'password:api'` ### present 驗證欄位必須存在於輸入資料中,但可以為空 ### regex:pattern 驗證欄位必須與指定的正則表達式匹配。 驗證時,這個規則使用 PHP 的 preg_match() 。 指定的模式應遵循 preg_match() 所需的相同格式,也包括有效的分隔符。 例如: 'email' => 'not_regex:/^.+$/i' > 注意: > > 當使用 regex / not_regex 模式時, 可能需要在陣列中指定規則,而不是使用 | 分隔符 ,特別是在正則表達式包含 | 字元的情況下 ### required 驗證的欄位必須存在於輸入資料中,而不是空。如果滿足以下條件之一,則欄位被視為「空」: 值為 null。 值為空字串。 值為空陣列或空 Countable 對象。 值為無路徑的上傳檔案 ### required_if:anotherfield,value,... 如果其它欄位 _anotherfield_ 為任一值( _value1_ 或 _value2_ 或 _value3_ 等,也可只有一個 _value1_) ,則此驗證欄位必須存在且不為空 如果您需要建構更複雜的條件 required_if 規則, 可以使用 Rule::requiredIf 方法。這個方法可以接受一個布林值或是一個 Closure函數,當傳入 Closure 函數時, Closure應該回傳 true 或 false ,以表明是否需要驗證此欄位 ``` use Illuminate\Support\Facades\Validator; use Illuminate\Validation\Rule; Validator::make($request->all(), [ 'role_id' => Rule::requiredIf($request->user()->is_admin), ]); Validator::make($request->all(), [ 'role_id' => Rule::requiredIf(function () use ($request) { return $request->user()->is_admin; }), ]); ``` ### required_unless:anotherfield,value,... 如果其它欄位 _anotherfield_ 不等於任一值 _value_ ,則此驗證欄位必須存在且不為空 ### required_with:foo,bar,... 在其他任一指定欄位出現時,驗證的欄位才必須存在且不為空 ### required_with_all:foo,bar,... 只有在其他指定欄位全部出現時,驗證的欄位才必須存在且不為空 ### required_without:foo,bar,... 在其他指定任一欄位不出現時,驗證的欄位才必須存在且不為空 ### required_without_all:foo,bar,... 只有在其他指定欄位全部不出現時,驗證的欄位才必須存在且不為空 ### same:field 驗證欄位的值必須與指定欄位的值相同 ### size:value 驗證欄位必須與指定值的大小一致。對於字串,value 對應字元數。對於數字,value 對應給定的整數值(attribute 必須有 numeric 或者 integer 規則)。對於陣列,size 對應陣列的 count 值。對於檔案,size 對應檔案大小(單位 kB)。讓我們來看幾個例子: ``` // 驗證字串長度是否為 12... 'title' => 'size:12'; // 驗證數字是否為 10... 'seats' => 'integer|size:10'; // 驗證陣列的長度(擁有的元素)是否為 5... 'tags' => 'array|size:5'; // 驗證上傳的檔案是否為 512 kB... 'image' => 'file|size:512'; ``` ### starts_with:foo,bar,... 驗證欄位必須以指定值之一開頭 ### string 驗證欄位必須是一個字串。如果允許這個欄位為 null,需要給這個欄位分配 nullable 規則 ### timezone 驗證欄位必須為符合 PHP 函數 timezone_identifiers_list() 所定義的有效時區標識 ### unique:table,column,except,idColumn 驗證欄位在指定的資料庫表格中必須是唯一的 #### 指定自定義資料表 / 欄位名: 除直接指定表名外,你也可以指定 Eloquent 模型 `'email' => 'unique:App\Models\User,email_address'` column 選項可用於指定相應資料庫列的欄位。 如果未指定 column 選項,則使用欄位本身名稱 `'email' => 'unique:users,email_address'` #### 自定義資料庫連接 有時你可能需要為驗證器創建的資料庫查詢設置自定義連接。上面的例子中,將 unique:users 設置為驗證規則,等於使用預設資料庫連接來查詢資料庫。如果要對其進行修改,請使用「點」語法來指定連接和表格名: `'email' => 'unique:connection.users,email_address'` 強制 Unique 規則忽略指定 ID: 有時,你可能希望在進行欄位唯一性驗證時忽略指定 ID 。例如, 在「更新個人資料」頁面會包含用戶名、郵箱和地點。這時你會想要驗證更新的 E-mail 值是否唯一。如果用戶僅更改了用戶名欄位而沒有改 E-mail 欄位,就不需要拋出驗證錯誤,因為此用戶已經是這個 E-mail 的擁有者了 使用 Rule 類別定義規則來指示驗證器忽略用戶的 ID 。這個例子中通過陣列來指定驗證規則,而不是使用 | 字元來分隔: ``` use Illuminate\Support\Facades\Validator; use Illuminate\Validation\Rule; Validator::make($data, [ 'email' => [ 'required', Rule::unique('users')->ignore($user->id), ], ]); ``` > 注意: > > 您永遠不應該將任何用戶控制的請求輸入傳遞給 ignore() 。您應該只通過 Eloquent 模型的實例來傳遞系統生成的唯一 ID,例如自動遞增 ID 或 UUID 。否則你的應用將更容易受到 SQL 注入攻擊 您可以傳遞整個模型實例,而不是將模型實例的主鍵值傳遞給 ignore() 。 Laravel 將自動從模型實例中獲取主鍵值: `Rule::unique('users')->ignore($user)` 如果你的資料表使用的主鍵名稱不是 id ,那就在呼叫 ignore() 時指定欄位的名稱: `Rule::unique('users')->ignore($user->id, 'user_id')` 預設情況下, unique 規則將檢查與要驗證欄位名稱相匹配的欄位的唯一性。 但是你可以傳遞一個不同的欄位名作為 unique 方法的第二個參數 `Rule::unique('users', 'email_address')->ignore($user->id),` #### 增加額外的 Where 語句: 你也可以通過 where() 指定額外的查詢條件。例如我們添加 account_id 為 1 的限制: ``` 'email' => Rule::unique('users')->where(function ($query) { return $query->where('account_id', 1); }) ``` ### url 驗證的欄位必須是有效的 URL ### uuid 驗證欄位必須是有效的 RFC 4122(版本 1,3,4 或 5)通用唯一標識符(UUID) ## 按條件增加規則 ### 欄位包含特定值跳過驗證 如果另一個欄位具有指定的值,你希望不驗證指定欄位。您可以使用 exclude_if 驗證規則來實現這一點。在本例中,如果 has_appointment 欄位的值為 false ,則不會驗證 appointment_date 和 doctor_name 欄位,因為如果沒有預約將導致另外兩個欄位為空: ``` use Illuminate\Support\Facades\Validator; $validator = Validator::make($data, [ 'has_appointment' => 'required|bool', 'appointment_date' => 'exclude_if:has_appointment,false|required|date', 'doctor_name' => 'exclude_if:has_appointment,false|required|string', ]); ``` 你可以使用 exclude_unless 規則來驗證指定欄位,除非另一個欄位具有指定的值 ``` $validator = Validator::make($data, [ 'has_appointment' => 'required|bool', 'appointment_date' => 'exclude_unless:has_appointment,true|required|date', 'doctor_name' => 'exclude_unless:has_appointment,true|required|string', ]); ``` #### 存在時則驗證 在某些情況下,你可能希望將要驗證的欄位存在於輸入陣列中時,才對該欄位執行驗證。可以在規則列表中增加 sometimes 來實現 ``` $v = Validator::make($request->all(), [ 'email' => 'sometimes|required|email', ]); ``` 在上面的例子中, email 欄位只有在 $data 陣列中存在時才會被驗證 > 技巧: > > 如果你嘗試驗證應該始終存在但可能為空的欄位,請查閱可選欄位的注意事項 #### 複雜條件驗證 有時候你可能需要增加基於更複雜的條件邏輯的驗證規則。例如,你可以希望某個指定欄位在另一個欄位的值超過 100 時才為必填。或者當某個指定欄位存在時,另外兩個欄位才能具有指定的值。增加這樣的驗證條件並不難。首先,使用靜態規則創建一個 Validator 實例: ``` use Illuminate\Support\Facades\Validator; $validator = Validator::make($request->all(), [ 'email' => 'required|email', 'games' => 'required|numeric', ]); ``` 假設我們有一個專為遊戲收藏家所設計的網頁應用,如果遊戲收藏家收藏超過一百款遊戲,我們會希望他們來說明下為什麼他們會擁有這麼多遊戲。比如說他們有可能經營了一家遊戲店,或者只是為了享受收集的樂趣。為了在特定條件下加入此驗證需求,可以在 Validator 實例中使用 sometimes() ``` $v->sometimes('reason', 'required|max:500', function ($input) { return $input->games >= 100; }); ``` 傳遞給 sometimes() 的第一個參數是我們需要有條件驗證的名稱欄位,第二個參數是我們想要添加的規則,如果作為第三個參數的 Closure 回傳 true,則規則被添加。該方法讓建構複雜條件驗證變得簡單,你甚至可以一次為多個欄位添加條件驗證: ``` $v->sometimes(['reason', 'cost'], 'required', function ($input) { return $input->games >= 100; }); ``` > 技巧: > > 傳遞給 Closure 的 $input 參數是 Illuminate\Support\Fluent 實例,可用於訪問輸入和檔案 ## 驗證陣列 驗證表單的輸入為陣列的欄位再也不會難為你了。 你可以使用「點」方法來驗證陣列中的屬性。例如, 如果傳入的 HTTP 請求中包含 photos[profile] 欄位,可以如下來驗證: ``` use Illuminate\Support\Facades\Validator; $validator = Validator::make($request->all(), [ 'photos.profile' => 'required|image', ]); ``` 我們還可以驗證陣列的每個元素,例如要驗證指定陣列輸入中每個 email 是否是唯一的,可以這麼做: ``` $validator = Validator::make($request->all(), [ 'person.*.email' => 'email|unique:users', 'person.*.first_name' => 'required_with:person.*.last_name', ]); ``` 相同地,在本地化語言檔案中你也可以使用 * 字元指定驗證訊息,從而可以使用單個驗證訊息定義基於陣列欄位的驗證規則: ``` 'custom' => [ 'person.*.email' => [ 'unique' => 'Each person must have a unique email address', ] ], ``` ## 自定義驗證規則 ### 使用規則物件 儘管 Laravel 提供了多樣化有用的驗證規則;但你亦可進行自定義。註冊自定義驗證規則的方法之一便是使用規則物件。你可以使用 make:rule 生成新的規則物件。接下來我們使用該命令生成一個驗證字串是否為大寫的規則, Laravel 會將新規則置於 app/Rules 資料夾中: `php artisan make:rule Uppercase` 當規則建立成功後,我們便可定義其行為。規則物件包含兩個方法: passes 和 message 。 passes() 接收屬性值及其名稱,它應該回傳以 true 和 false 表示的屬性值是否通過驗證的結果。 message() 應該回傳驗證失敗時使用的錯誤訊息: ``` <?php namespace App\Rules; use Illuminate\Contracts\Validation\Rule; class Uppercase implements Rule { /** * Determine if the validation rule passes. * * @param string $attribute * @param mixed $value * @return bool */ public function passes($attribute, $value) { return strtoupper($value) === $value; } /** * Get the validation error message. * * @return string */ public function message() { return 'The :attribute must be uppercase.'; } } ``` 如果你想要從本地化檔案中取得錯誤訊息,你可以在 message() 中使用 trans() 幫助函式: ``` /** * Get the validation error message. * * @return string */ public function message() { return trans('validation.uppercase'); } ``` 一旦定義了規則,你便可以通過將規則的實例化與其他驗證規則一起傳遞給驗證器: ``` use App\Rules\Uppercase; $request->validate([ 'name' => ['required', 'string', new Uppercase], ]); ``` ## 使用 Closures 如果你的規則在應用中僅僅使用一次,便可使用 Closure 來代替規則物件。 Closure 接收屬性的方法,屬性的值以及在驗證失敗時的回呼函數 $fail: ``` use Illuminate\Support\Facades\Validator; $validator = Validator::make($request->all(), [ 'title' => [ 'required', 'max:255', function ($attribute, $value, $fail) { if ($value === 'foo') { $fail('The '.$attribute.' is invalid.'); } }, ], ]); ``` ## 隱式規則 預設當屬性被驗證時並不存在或包含空字串,那麼不管是一般的驗證規則又或者是自定義規則,都不會執行 例如, unique 規則對於空字串將不會執行 ``` use Illuminate\Support\Facades\Validator; $rules = ['name' => 'unique:users,name']; $input = ['name' => '']; Validator::make($input, $rules)->passes(); // true ``` 如果希望自定義規則能在空屬性情況下也要執行,該規則必須暗示屬性是必須的。為了要建立一個隱式規則,只需要實作 Illuminate\Contracts\Validation\ImplicitRule 介面。這個介面只做為驗證器的標示作用;因此你不需要去實作任何額外的方法 但隱式規則僅說明該屬性是必須的,至於如何判定是不存在或空屬性就要看你自己了 ## 懶人包 取得所有欄位 $request->all(); 取得所有欄位,但排除部分欄位 $request->except([要排除的欄位]); 取得部分欄位 $request->only([要取得的欄位]); 取得單一欄位 $request->input(單一欄位,該欄位不存在的預設值); 確認某欄位是否有填寫 $request->filled(欄位名稱); 取得JSON的單一欄位,用於Content-Type未指定為JSON時 $request->json(欄位名稱); 取得檔案欄位的內容 $request->file(欄位名稱); ## 表單資料驗證 ### 控制器驗證 直接使用控制器實例來進行驗證,適用於喜歡直接在Controller裡面做驗證 ``` //app\Http\Controllers\ItemController.php public function store(Request $request) { $this->validate($request,[ 'title' => 'required|max:5', 'size' => 'required' ]); //驗證成功,可存入資料 } ``` ### 手動建立驗證器 適用於希望介入當驗證失敗後的處理 ``` //app\Http\Controllers\ItemController.php use Validator; public function store(Request $request) { $validator = Validator::make($request->all(),[ 'title' => 'required|max:5', 'size' => 'required' ]); if($validator->fails()){ //我的錯誤處理 //返回表單頁面,傳回錯誤與用戶輸入的值 return redirect('items/create')->withErrors($validator)->withInput(); } //驗證成功,可存入資料 } ``` ### 生成表單驗證類別 適用於喜歡將驗證邏輯移出控制器為單獨檔案 建立驗證類別 `php artisan make:request Create{Item}Request` 編輯驗證類別 ``` //app\Http\Requests\CreateItemRequest.php //驗證該使用者是否有權限來提交此表單請求,如無權限將跳出403錯誤 public function authorize() { return true; } //表單驗證規則 public function rules() { return [ 'title' => 'required|max:5', 'size' => 'required' ]; } ``` 在控制器方法啟用此驗證類別,把Action的$request類別改為新增的驗證類別 ``` //app\Http\Controllers\ItemController.php use App\Http\Requests\CreateItemRequest; public function store(CreateItemRequest $request){ //驗證成功,可存入資料 } ``` ### 要確認指定欄位是否有錯誤 ### 視圖錯誤訊息顯示 要顯示指定欄位的第一個錯誤 ``` @if ($errors->has('size')) <div style="color:red">{{ $errors->first('size')}}</div> @endif ``` 要在畫面上顯示所有的錯誤訊息 ``` @if ($errors->any()) @foreach ($errors->all() as $error) <div style="color:red">{{$error}}</div> @endforeach @endif ``` ### 將錯誤訊息改為中文或自定義的內容 複製resources/lang/en/validation.php到resources/lang/zh_TW/validation.php 將裏頭的內容修改成所要的訊息或中文語系 ``` <?php return [ /* |-------------------------------------------------------------------------- | Validation Language Lines |-------------------------------------------------------------------------- | | The following language lines contain the default error messages used by | the validator class. Some of these rules have multiple versions such | as the size rules. Feel free to tweak each of these messages here. | */ 'accepted' => ':attribute是被接受的', 'active_url' => ':attribute必須是一個合法的 URL', 'after' => ':attribute是 :date 之後的一個日期', 'alpha' => 'attribute必須全部由字母字符構成。', 'alpha_dash' => ':attribute必須全部由字母、數字、中劃線或下劃線字符構成', 'alpha_num' => ':attribute必須全部由字母和數字構成', 'array' => ':attribute必須是個數组', 'before' => ':attribute 必須是 :date 之前的一個日期', 'between' => [ 'numeric' => ':attribute 必須在 :min 到 :max之間', 'file' => ':attribute 必須在 :min 到 :max KB之間', 'string' => ':attribute 必須在 :min 到 :max 個字符之間', 'array' => ':attribute 必須在 :min 到 :max 項之間', ], 'boolean' => ':attribute 字符必須是 true 或 false', 'confirmed' => ':attribute 二次輸入不相同', 'date' => ':attribute必須是一个合法的日期', 'date_format' => ':attribute 與给定的格式 :format 不符合', 'different' => ':attribute 必須不同於:other', 'digits' => ':attribute必須是 :digits 位', 'digits_between' => ':attribute 必須在 :min and :max 位之間', 'dimensions' => ':attribute的圖片比例無效', 'distinct' => 'The :attribute欄位的值重複.', 'email' => ':attribute必須是一个合法的電子郵箱地址。', 'exists' => '選取的 :attribute 是無效的.', 'file' => ':attribute 必須是一個檔案', 'filled' => ':attribute 屬性是必須的.', 'image' => ':attribute 必須是一個圖片 (jpeg, png, bmp 或者 gif)', 'in' => '選定的 :attribute 是無效的', 'in_array' => ':attribute 欄位不存在於 :other裡頭', 'integer' => ':attribute 必須是個整數', 'ip' => ':attribute 必須是一個合法的 IP 地址。', 'json' => ':attribute 必須是合法的JSON字串', 'max' => [ 'numeric' => ':attribute 的最大長度為:max位', 'file' => ':attribute 最大為:max KB', 'string' => ':attribute 的最大長度為:max字元', 'array' => ':attribute 的最大個數為:max個', ], 'mimes' => ':attribute 的文件類型必須是:values', 'min' => [ 'numeric' => ':attribute的最小長度為:min位', 'file' => ':attribute 大小至少為:min KB', 'string' => ':attribute的最小長度為:min字元', 'array' => ':attribute 至少有 :min 項', ], 'not_in' => '選取的 :attribute 是無效的', 'numeric' => ':attribute 必須是數字', 'present' => ':attribute 欄位必須是存在的', 'regex' => ':attribute 格式無效', 'required' => ':attribute 欄位是必須的', 'required_if' => ':attribute 欄位是必須的當 :other 欄位是 :value.', 'required_unless' => ':attribute 欄位是必須的除非 :other 為這些 :values.', 'required_with' => ':attribute 欄位是必須的當 :values 是存在的', 'required_with_all' => ':attribute 欄位是必須的當 :values 都是存在的', 'required_without' => ':attribute 欄位是必須的當 :values 是不存在的', 'required_without_all' => ':attribute 欄位是必須的當 :values 沒有半個存在', 'same' => ':attribute和:other必須相符', 'size' => [ 'numeric' => ':attribute 必須是 :size 位', 'file' => ':attribute 必須是 :size KB', 'string' => ':attribute 必須是 :size 个字符', 'array' => ':attribute 必須包括 :size 項', ], 'string' => ':attribute 必須是字串', 'timezone' => ':attribute 必須是个有效的時區', 'unique' => ':attribute 已經存在', 'url' => ':attribute 格式不正確', /* |-------------------------------------------------------------------------- | Custom Validation Language Lines |-------------------------------------------------------------------------- | | Here you may specify custom validation messages for attributes using the | convention "attribute.rule" to name the lines. This makes it quick to | specify a specific custom language line for a given attribute rule. | */ 'custom' => [ 'attribute-name' => [ 'rule-name' => 'custom-message', ], 'g-recaptcha-response' => [ 'required' => '請確認您不是機器人.', 'captcha' => '驗證錯誤! 請刷新表單後重新上傳.', ], ], /* |-------------------------------------------------------------------------- | Custom Validation Attributes |-------------------------------------------------------------------------- | | The following language lines are used to swap attribute place-holders | with something more reader friendly such as E-Mail Address instead | of "email". This simply helps us make messages a little cleaner. | */ 'attributes' => [ 'chkPwd' => '確認密碼', 'newPwd' => '密碼', 'email' => '電子郵箱', 'username' => '帳號', 'password' => '密碼', 'serial' => '商品序號', 'lang' => '語言', 'name' => '名稱', 'price' => '價格', 'cabinet_no' => '櫃號', 'link' => '連結', 'image' => '圖片', 'code' => '條碼', 'en_name' => '英文名字', 'stock' => '數量', 'cgy_id' => '商品類別', 'company_id' => '公司行號', 'sort' => '排序', 'qty' => '購買數量', 'address' => '地址', 'manager' => '管理者姓名', 'contact' => '聯絡電話', 'guardLtd' => '社區保全公司', 'pic' => '圖片', 'title' => '標題', 'url' => '網址', 'owner_name' => '收件人', 'content' => '內容', 'fee' => '費用', 'contacter' => '聯絡人', 'mobile' => '手機號碼', 'type' => '類型', 'tags_list' => '標籤', 'mode' => '模式', 'mediums' => '文章媒體', 'subject' => '主旨', ], ]; ``` ### 常用驗證規則 * email 電子郵箱 * url 網址 * required 必填 * file 檔案 * image 圖片 * integer 整數 * json JSON格式 * min 最小值 * max 最大值 * size 整數 [所有的驗證規則文件](https://laravel.com/docs/7.x/validation#available-validation-rules)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully