在這里我嘗試了兩種方法(新增驗證類 和直接更改規則)修改驗證規則
1.1 新增一個驗證手機號碼類,輸入 php artisan make:rule CheckMobile 然后修改該類
namespace App\Rules; use Illuminate\Contracts\Validation\Rule; class Checkmobile implements Rule { /** * Create a new rule instance. * * @return void */ public function __construct() { // } /** * Determine if the validation rule passes. * * @param string $attribute * @param mixed $value * @return bool */ public function passes($attribute, $value) { return preg_match('/^1[34578][0-9]{9}$/', $value); } /** * Get the validation error message. * * @return string */ public function message() { return '請填寫正確的手機號碼!'; } }
1.2 在注冊控制器中引用
use App\Rules\Checkmobile;
...
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|string|max:8', 'email' => 'required|string|email|max:255|unique:users', 'password' => 'required|string|min:6|confirmed', 'college' => 'required|string|max:20', 'class' => 'required|string|max:20', 'phone'=> ['required|mobile', new Checkmobile] ],
.....
2.1 使用 Validator::extend() 直接修改
protected function validator(array $data) { Validator::extend('mobile', function($attribute, $value, $parameters) { return preg_match('/^1[34578][0-9]{9}$/', $value); }); return Validator::make($data, [ 'name' => 'required|string|max:8', 'email' => 'required|string|email|max:255|unique:users', 'password' => 'required|string|min:6|confirmed', 'college' => 'required|string|max:20', 'class' => 'required|string|max:20', 'phone'=> 'required|mobile', ], [ "min" => ":attribute 至少為 :min 位", "confirmed" => "兩次輸入 :attribute 不一致!", "required" => ":attribute 不能為空!", "mobile" => ":attribute 格式不正確!" ], [ "name" => "昵稱", "password" => "密碼", "phone" => "手機號碼", "college" => "院校", "class" => "班級" ]);
順帶一提,這里雖然用
Validator::make() 將字段指定為中文, 我還是引入了中文包