I'm not sure I quite get the scenario, but you might want to look at conditional rules: http://laravel.com/docs/validation#conditionally-adding-rules
I think you need to make it required (if the other option is set), otherwise the field is optional
Thanks elite123, I hadn't seen the 'sometimes' attribute before. I don't think it quite works for what I'm doing though (maybe I'm just not connecting the dots?).
As an example, I have a validator that requires a field only if a certain value is in an array (from HTML checkboxes). The problem is that just using Validate::extend(), it doesn't require this check. In other words, it only runs the validation against the value if it's present, it doesn't fail if it isn't. In order to require the check, I had to call on the Validator->addImplicitExtension() method. This works but I feel like it breaks the separation of logic because now I have validation declarations (acting on an instance of the Validation class) inside my CustomValidator class. Smells bad. :)
Am I missing something? Is there another way to do this?
This is probably a bit late, but for whoever this might be helpful. To create implicit extensions, use
Validator::extendImplicit( 'validator_name', function($attribute, $value, $parameters)
{
});
Now the validation rule will run even if the value is empty.
What if instead closure I want to extend the Validator class itself like shown in laravel 4.2 docs. How can I create implicit method extension ?
<?php
class CustomValidator extends Illuminate\Validation\Validator {
public function validateFoo($attribute, $value, $parameters)
{
return $value == 'foo';
}
}
A bit late, i know (also my first post here). This is what you can do:
<?php
class CustomValidator extends Illuminate\Validation\Validator {
public function __construct( $translator, $data, $rules, $messages = array(), $customAttributes = array() )
{
parent::__construct( $translator, $data, $rules, $messages, $customAttributes );
$this->implicitRules[] = Str::studly('foo_bar');
}
public function validateFooBar($attribute, $value, $parameters)
{
return $value == 'foo' || $value == 'bar';
}
}
Just add the rule to the $implicitRules array.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community