首页 » Web技术 » Laravel » 正文

Laravel 5.5 自定义验证规则

Laravel 5.5 新增的一个功能是自定义验证规则,关于这个功能,Taylor 还写了一个快速教程

这里是验证规则的一个简单用例:

<?php
use App\Rules\ValidRepository;
$request->validate([
    'repository' => [
        'required', 
        new ValidRepository($this->source(), $request->branch)
    ]
]);

这里是做校验的 ValidRepository:

<?php
namespace App\Rules;
use App\Source;
use Illuminate\Contracts\Validation\Rule;
class ValidRepository implements Rule
{
    /**
     * The source control provider instance.
     *
     * @var \App\Source
     */
    public $source;
    /**
     * The branch name.
     *
     * @var string
     */
    public $branch;
    /**
     * Create a new rule instance.
     *
     * @param  \App\Source  $source
     * @param  string  $branch
     * @return void
     */
    public function __construct($source, $branch)
    {
        $this->source = $source;
        $this->branch = $branch;
    }
    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        if (! $this->source instanceof Source) {
            return false;
        }
        return $this->source->client()->validRepository(
            $value, $this->branch
        );
    }
    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The given repository is invalid.';
    }
}

想了解更完整的信息,可以查看 Taylor 的文章,里面有关于这个功能的更多详情。


该篇属于专题:《Laravel 5.5 资讯

发表评论