Alexandre Demelas
Alexandre Demelas

Reputation: 4690

Laravel Validation: How to access rules of an attribute in customized validation

In below rules, I have my custom validation customRule: *date*

$rules = [
  'my_date' => 'required|date_format: Y-m-d|customRule: someDate',
];

Inside my custom validation rules extension, I need to access the date_format attribute of the rule:

Validator::extend('customRule', function($attribute, $value, $parameters) {

   $format = $attribute->getRules()['date_format']; // I need something like this 

   return $format == 'Y-m-d';
});

How can I get the rule value of certain attribute on an extended validator?

Upvotes: 1

Views: 1885

Answers (1)

jedrzej.kurylo
jedrzej.kurylo

Reputation: 40909

You can't access other rules. Validators are to be independent units - the only data they should use is:

  • value of field being validated
  • values passed to this validation rule as parameters
  • values of other attributes of object being validated

It seems that what you need is a custom validator that would wrap what is date_format and customRule doing:

Validator::extend('custom_date_format', function($attribute, $value, $parameters) {
  $format = $parameters[0];
  $someDate = $parameters[1];

  $validator = Validator::make(['value' => $value], ['value' => 'date_format:' . $format]);

  //validate dateformat
  if ($validator->fails()) {
    return false;
  }

  //validate custom rule using $format and $someDate and return true if passes
});

Once you have it, you can use it like that:

$rules = [
  'my_date' => 'required|custom_date_format:Y-m-d,someDate',
];

Upvotes: 1

Related Questions