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

3

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

我想使用我的自定义规则,叫做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],
]);

4
看起来你正在使用正则表达式验证字符串,相同的逻辑可以通过正则表达式内置的验证方法实现。查看文档:https://laravel.com/docs/5.5/validation#rule-regex 无需创建自己的验证规则。 - Rutvij Kothari
4
如果你想使用验证,把它放进一个数组里。像这样:'email' => ['required', 'email', new employeemail] - Rutvij Kothari
4
啊,谢谢你。那我会使用正则表达式规则,我忘了这个。还有感谢你提到如何在请求文件中使用自定义规则。 - Knack Kwenie
1个回答

4

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

看起来你是使用正则表达式验证字符串,相同的逻辑可以通过内置的正则表达式验证方法实现。看看这个。 laravel.com/docs/5.5/validation#rule-regex 没有必要创建自己的验证规则。- Rutvij Kothari

如果您想使用您的验证,请将其传入数组中。像这样。 'email' => ['required', 'email', new employeemail]


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接