本文透過簡易的Laravel livewire範例,
看看livewire元件如何驗證使用者輸入錯誤,並顯示中文錯誤訊息。
功能測試,活動名稱不填,並且網址亂打後,送出表單。
在下圖畫面中「紅色」的字我們可以看見是非常友善的中文化的錯誤訊息啦。
一、首先設定config/app.php,加入環境變數,並且預設中文。
這樣.env中不需調整預設就吃中文語言檔。
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by the translation service provider. You are free to set this value
| to any of the locales which will be supported by the application.
|
*/
'locale' => env("APP_LOCALE","zh_TW"),
二、放入中文化語言檔的lang/zh_TW/validation.php,網路上應該Google的到。
如果您google不到,那直接拿自己Laravel專案目錄下的lang/en/validation.php翻吧.😱
三、過於簡單,直接看我的元件的Class吧,
$rules直接設定規則及$validationAttributes設定好input欄位的中文名稱。
class RedirectUrlsForm extends Component
{
use Common;
public $listeners = ['setOaName'];
public $redirect_url_id;
public $action_name;
public $action_key;
public $target_url;
public $tags;
public $errors = [];
protected $rules = [
'action_name' => 'required',
'target_url' => 'required|url',
'oa_id'=>'required'
];
protected $validationAttributes = [
'action_name' => '活動名稱',
'target_url' => '導向網址'
];
public function store(){
$validatedData=$this->validate();
RedirectUrl::create($validatedData);
}
public function render()
{
return view('livewire.redirect-urls-form');
}
}
上方程式碼中檢查規則,符合規則放行,表單資料直接存入Model啦。
$rules的地方理論上要定義所有的欄位,可不填的就打nullable。
如果要對欄位資料進行特殊處理,就分開update,正常情況下相關方便。
$validatedData=$this->validate();
四,這是Laravel livewire的view部份內容,
可以看到表單submit時,會呼叫store()的方式。
{{-- RedirectUrlsForm --}}
<div class="row root">
<label class="d-none rootlabel">{{ $this->getName() }}</label>
<div class="col-12 col-sm-6 col-lg-6">
<div class="card" id="sample-login">
<form wire:submit.prevent="store">
<div class="card-body pb-0">
<p class="text-muted">請填寫活動的名稱及活動網址</p>
<div class="form-group">
<label>活動名稱 @error("action_name")<span class="text-danger">{{$message}}!@enderror</span></label>
<div class="input-group mb-3">
<span class="input-group-text"><i class="fa-solid fa-flag-pennant"></i></span>
<input type="text" wire:model="action_name" class="form-control" placeholder="可識別的名稱" aria-label="活動名稱" aria-describedby="basic-addon1">
</div>
</div>
<div class="form-group">
<label>導向網址 @error("target_url")<span class="text-danger">{{$message}}!</span>@enderror</label>
<div class="input-group">
<span class="input-group-text" id="basic-addon2"><i class="fa-sharp fa-solid fa-link-horizontal"></i></span>
<input type="text" wire:model="target_url" class="form-control" placeholder="跳轉的活動網址" aria-label="導向網址" aria-describedby="basic-addon2">
</div>
</div>
五、驗證功能,表單亂打,
如同上方的截圖中可直接顯示出正確的中文錯誤訊息。
在View的部份,錯誤訊息就可以顯示出中文字了
「導向網址的格式錯誤」及「請填寫活動名稱」。
詳細的使用方式也可以自行去查看Laravel Livewire的官網 ,寫的很清楚。
@error("action_name")<span class="text-danger">{{$message}}!@enderror
本範例採用Laravel框架9.31.0進行
artisan -V
Laravel Framework 9.31.0
No Comment
Post your comment