Laravel內置的驗證規則不夠用?
沒事,那我們就自己來添加規則
在 laravel 的 app\Providers\AppServiceProvider.php 這個文件中,boot 方法下可以自己添加規則
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Validator;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//手機號
Validator::extend('mobile', function($attribute, $value, $parameters) {
return preg_match('/^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\d{8}$/', $value);
});
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}
這樣,我們的代碼就“打入內部”了,可以在 Validator 中直接使用
然後找到你的語言包
我的修改過,所以在
加入自定義錯誤信息
<?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.
|
*/
'mobile' => '手機號格式錯誤',
// ......
];
這樣就配置好了,很方便吧