2

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

Community
  • 1
  • 1
Macks
  • 1,696
  • 5
  • 23
  • 38

2 Answers2

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.

Jason Lewis
  • 18,537
  • 4
  • 61
  • 64
  • Hi Jason, thank you for your help. I've implemented your suggestion and it works great, but I can't get rid of the feeling that a custom class would be cleaner. What do I need to know to understand how I can get this running? – Macks Jun 04 '13 at 09:11
0

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

public function validateTimezone($attribute, $value, $parameters) {
    return !empty(Timezones::$timezones[$value]);
}
sybear
  • 7,837
  • 1
  • 22
  • 38
  • Hey Jari, thank you for your help. Removing `static` doesn't change anything unfortunately. – Macks Jun 03 '13 at 14:47