我创建了一个注册表,农民将在其中输入他的名字。该名称可能包含连字符或空格。验证规则写在app/http/requests/farmerRequest.php
文件中:
public function rules()
{
return [
'name' => 'required|alpha',
'email' => 'email|unique:users,email',
'password' => 'required',
'phone' => 'required|numeric',
'address' => 'required|min:5',
];
}
但是问题是name
字段由于alpha
规则而不允许任何空格。 name
字段为varchar(255) collation utf8_unicode_ci
。
我应该怎么做,以便用户可以输入带有空格的姓名?
您可以使用仅允许字母,连字符和空格的Regular Expression Rule:
public function rules()
{
return [
'name' => 'required|regex:/^[\pL\s\-]+$/u',
'email' => 'email|unique:users,email',
'password' => 'required',
'phone' => 'required|numeric',
'address' => 'required|min:5',
];
}
您可以为此创建自定义验证规则,因为这是您可能想在应用程序的其他部分(或您的下一个项目)中使用的非常普遍的规则。
在您的app / Providers / AppServiceProvider.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',
];
}
您可以使用This Regular Expression验证您的输入请求。但是,您应该仔细编写要执行的RegEx规则。
在这里,您可以使用此正则表达式来验证只允许使用字母和空格。
public function rules()
{
return [
'name' => ['required', 'regex:/^[a-zA-Z\s]*$/']
];
}
我知道,这个答案可能会与其他人有所改变。但是,这就是为什么我要进行一些更改的原因:
不要误会我的意思。我知道,其他答案很好。但是我认为最好根据需要验证所有内容,以便我们保护应用程序的安全。