gpt4 book ai didi

php - Laravel 5.5 在验证请求文件中使用自定义验证规则?

转载 作者:可可西里 更新时间:2023-11-01 00:55:07 24 4
gpt4 key购买 nike

是否可以在验证请求文件中使用我的自定义验证规则?

我想使用名为 EmployeeMail 的自定义规则这是请求文件的代码

class CoachRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}

/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
$rules = [];

if ($this->isMethod('post') ) {
$rules = [
'name' => 'required|string',
'email' => 'required|email|employeemail', <<<--- this
'till' => 'required|date_format:H:i|after:from',
];
}

//TODO fix this
//TODO add custom messages for every field

return $rules;
}
}

当我尝试像这样使用它时它给我一个错误

方法 [validateEmployeemail] 不存在。

自定义规则代码

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class EmployeeMail 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)
{
// If mail is that of an employee and not a student pass it
return preg_match("/@test.nl$/", $value) === 1;
}

/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return 'Email is geen werknemers mail';
}
}

我只能像这样使用这个自定义规则吗?

$items = $request->validate([
'name' => [new FiveCharacters],
]);

最佳答案

Rutvij Kothari 在评论中回答了这个问题。

看来您正在使用正则表达式验证字符串,同样的逻辑可以通过正则表达式内置验证方法来实现。看看这个。 laravel.com/docs/5.5/validation#rule-regex 无需创建自己的验证规则。 – Rutvij Kothari

如果你想使用你的验证,将它传递到一个数组中。像这样。 'email' => ['required', 'email', new employeemail]

关于php - Laravel 5.5 在验证请求文件中使用自定义验证规则?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47915461/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com