Extending Custom Validation-Class

左心房为你撑大大i 提交于 2019-12-11 02:53:14

问题


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

Validation-Class

<?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]);
    }

}

My rules are setup like this:

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

I call the Validator inside my model like this:

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

I get the following error:

BadMethodCallException

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.

Thank you for your help

Max


回答1:


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);

It then returns an instance of Illuminate\Validation\Validator.

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;
});

You can read more on this and on how to register your own resolver over on the official documentation.




回答2:


Is that function supposed to be static? What if you remove static?

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


来源:https://stackoverflow.com/questions/16897462/extending-custom-validation-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!