Laravel 4: Validate start and end date with before and after validation

后端 未结 5 1646
深忆病人
深忆病人 2021-01-27 07:22

I want to validate two date fields in a form which is from_date and end_date. Need to check from_date is less than end_date.

$rules = array(\'from_date\' => a         


        
5条回答
  •  独厮守ぢ
    2021-01-27 07:32

    Just came across this and thought I'd share an answer I found: Compare attributes in validation

    Basically, you'd create a new Validator that extends Illuminate\Validation\Validator and write a custom rule in there:

    public function validateEndAfter($attribute, $value, $parameters) {
        $start_date = $this->getValue($parameters[0]); // get the value of the parameter (start_date)
        return (strtotime($value) > strtotime($start_date));
    }
    

    then in your validator use the new rule:

    $rules = [
        'start_date'  => 'required',
        'end_date'=> 'required|end_after:start_date',
    ]
    

提交回复
热议问题