Laravel Validation is sometimes used for date validation

I currently have a validation rule that looks like this:

  public function rules()
  {
   return [
        'startDate' => 'required|sometimes|before_or_equal:endDate',
        'endDate' => 'sometimes|required|after_or_equal:startDate',
    ];
  }

      

Sometimes the option works the way I understand it, based on the fact that if the field is present, run the validation rule. However, if the end date is not sent or is zero, my rule before or equal hits and fails. In some cases in my application, the end date will be zero. Is there a way to "override" the startDate validation rule on this instance, or do I need to create a custom validator for this?

something like before_or_equal_when_present

?

+3


source to share


1 answer


You can use IF to add and manage rules in rule functions. You can access inputs referencing $ this like the request itself:

public function rules()
  {
   $rules = [
        'startDate' => 'required|sometimes|before_or_equal:endDate',
        'endDate' => 'sometimes|required|after_or_equal:startDate',
    ];

   if( $this->input('endDate') > 0)
          $rules['endDate'] = "rule". $rules['endDate']

   return $rules;
}

      



This is just a mock so you know you can manipulate and have access to the traversed fields.

0


source







All Articles