我创建了一个登记表,农民将输入他的名字.名称可能包含连字符或空格.验证规则写在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
.
我该怎么做,以便用户可以用空格输入他的名字?
您可以使用仅明确允许字母,连字符和空格的正则表达式规则:
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', ]; }