你可以为此创建自定义验证规则,因为这是一个非常常见的规则,你可能希望在应用的其他部分(或者可能在下一个项目)上使用。
在您的应用程序/提供商/应用程序服务提供程序上.php
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//Add this custom validation rule.
Validator::extend('alpha_spaces', function ($attribute, $value) {
// This will only accept alpha and spaces.
// If you want to accept hyphens use: /^[\pL\s-]+$/u.
return preg_match('/^[\pL\s]+$/u', $value);
});
}
在 resources/lang/en/validation 中定义自定义验证消息.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.
|
*/
// Custom Validation message.
'alpha_spaces' => 'The :attribute may only contain letters and spaces.',
'accepted' => 'The :attribute must be accepted.',
....
并像往常一样使用它
public function rules()
{
return [
'name' => 'required|alpha_spaces',
'email' => 'email|unique:users,email',
'password' => 'required',
'phone' => 'required|numeric',
'address' => 'required|min:5',
];
}