我有一个简单的注册表单,我使用此验证来创建新用户
$validator = Validator::make($request->all(), [
'first_name' => ['required'],
'last_name' => ['required'],
'phone' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', ],
]);
if ($validator->fails()) {
return response()->json(['message' => 'Errors!','errors'=>$validator->errors()], 500);
}else{
return response()->json(['message' => 'User registered successfully'], 201);
}
现在我需要制定一个验证规则,将姓氏和名字组合在一起并验证最大字符数
编写 Laravel 自定义验证规则
<?php
namespace App\Rules;
use Closure;
use Illuminate\Contracts\Validation\DataAwareRule;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Support\Str;
class FullNameMaxCharactor implements ValidationRule, DataAwareRule
{
protected $requestData=null;
/**
* Run the validation rule.
*
* @param \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail
*/
public function validate(string $attribute, mixed $value, Closure $fail): void
{
$fullNameCharacters= Str::length(data_get($this->requestData,'first_name').data_get($this->requestData,'last_name'));
if ($fullNameCharacters>10) {
$fail('The first and last name should be less than equal to 10.');
}
}
public function setData(array $data)
{
$this->requestData=$data;
return $this;
}
}
以及验证规则中
$validation=\Illuminate\Support\Facades\Validator::make($request->all(),[
'first_name' => ['required',new \App\Rules\FullNameMaxCharactor()],
'last_name' => ['required'],
'phone' => ['required', 'string', 'max:255'],
]);