扩展自定义验证类 [英] Extending Custom Validation-Class

查看:79
本文介绍了扩展自定义验证类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近一直在尝试使用Laravel 4,并且正在尝试使自定义验证类起作用.

I've been experimenting with Laravel 4 recently and am trying to get a custom validation-class to work.

<?php

class CountdownEventValidator extends Validator {

    public function validateNotFalse($attribute, $value, $parameters) {
        return $value != false;
    }

    public function validateTimezone($attribute, $value, $parameters) {
        return !empty(Timezones::$timezones[$value]);
    }

}

我的规则设置如下:

protected $rules = [
    'title' => 'required',
    'timezone' => 'timezone',
    'date' => 'not_false',
    'utc_date' => 'not_false'
];

我这样在模型内部调用验证器:

$validation = CountdownEventValidator::make($this->attributes, $this->rules);

我收到以下错误消息:

BadMethodCallException

BadMethodCallException

方法[validateTimezone]不存在.

Method [validateTimezone] does not exist.

我看了很多教程,但是我找不到我的代码出了什么问题.

I've looked up quite a few tutorials but I couldn't find out what's wrong with my code.

谢谢您的帮助

最大

推荐答案

尽管方法本身是非静态的,但是当您调用Validator::make时,实际上是在调用Illuminate\Validation\Factory::make.当您点击Validator类时,您将穿过立面,并且在后台,调用看起来像这样.

When you call Validator::make you're actually calling Illuminate\Validation\Factory::make although the method itself is non-static. When you hit the Validator class you're going through the facade and in the background the call looks something like this.

App::make('validator')->make($this->attributes, $this->rules);

然后返回Illuminate\Validation\Validator的实例.

您可以使用Validator::extend注册自己的规则,也可以注册自己的解析程序.我建议,现在,您只需使用Validator::extend用您自己的规则扩展验证器即可.

You can register your own rules with Validator::extend or you can register your own resolver. I recommend, for now, you just extend the validator with your own rules using Validator::extend.

Validator::extend('not_false', function($attribute, $value, $parameters)
{
    return $value != false;
});

您可以在官方网站上了解有关此内容以及如何注册自己的解析器的更多信息.文档.

这篇关于扩展自定义验证类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆