php - 拉拉维尔 : Group existing validation rules in single custom Rule?

标签 php laravel laravel-5 laravel-validation

是否可以在自定义规则中使用现有的 Laravel 验证规则?

示例:required|string|max:100 我只想将这些规则分组到一个规则 custom_rule_name 中。

无论是这样

Validator::extend('foo', function ($attribute, $value, $parameters, $validator) {
    return $value == 'required|string|max:100';//something like this
});

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class Uppercase implements Rule
{
    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        return $value == 'required|string|max:100';//something like this
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The :attribute must be uppercase.';
    }
}

请告诉我是否有可能?

谢谢

卡里姆

最佳答案

您可以在 passes() 函数内使用 Validator 外观。像这样:

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\Validator;

class Uppercase implements Rule
{
    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        $validator = Validator::make([$attribute => $value], [
            $attribute => 'required|string|max:100',
        ]);

        return !$validator->fails();
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The :attribute must be uppercase.';
    }
}

关于php - 拉拉维尔 : Group existing validation rules in single custom Rule?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52778081/

相关文章:

Angularjs 代码无法在 Chrome 中运行

laravel - 将 HTML 代码转换为 laravel(或任何框架)

php - Laravel 5.2 - 通过一个提交请求和带有行号的自定义验证消息将 n 行插入数据库

php - 在 Woocommerce 中结帐后更改订单总额

php - Laravel Sync 方法只发送第二个数据

php - Laravel Seed 更新另一个表上的列

php - 如何在 laravel 5.2 中检索行中的常用单词

javascript - 创建 JSON 时如何使用变量

php - ob_clean 不清理头文件前的输出?

php - Laravel 5.1 oAuth 2 服务器 'invalid scope' 错误