W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
為了避免進行危險性的操作,Nova 在創(chuàng)建 / 更新屏幕上顯示的任何 Nova 字段都需要進行一些驗證。值得慶幸的是,將你所熟悉的 Laravel 驗證規(guī)則附加到 Nova 資源字段中非常簡單。下面讓我們看看它是怎么使用的。
在資源上定義字段時,你可以使用 rules
方法將 驗證規(guī)則 附加到字段:
Text::make('Name')
->sortable()
->rules('required', 'max:255'),
當然,如果你正在使用 Laravel 的 驗證規(guī)則對象 , 你也可以將這些對象附加到資源當中:
use App\Rules\ValidState;
Text::make('State')
->sortable()
->rules('required', new ValidState),
當然,你也可以使用 自定義 Closure 驗證規(guī)則 來驗證資源字段:
use App\Rules\ValidState;
Text::make('State')
->sortable()
->rules('required', function($attribute, $value, $fail) {
if (strtoupper($value) !== $value) {
return $fail('The '.$attribute.' field must be uppercase.');
}
})
如果要定義僅在創(chuàng)建資源時應(yīng)用的規(guī)則,可以使用以下 creationRules
方法:
Text::make('Email')
->sortable()
->rules('required', 'email', 'max:255')
->creationRules('unique:users,email')
->updateRules('unique:users,email,{{resourceId}}'),
同樣,如果要定義僅在更新資源時應(yīng)用的驗證規(guī)則,則可以使用 updateRules
方法。如有必要,你可以在規(guī)則定義中使用占位符 resourceId
。此占位符將自動替換為正在更新的資源的主鍵:
Text::make('Email')
->sortable()
->rules('required', 'email', 'max:255')
->creationRules('unique:users,email')
->updateRules('unique:users,email,{{resourceId}}'),
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: