php - Laravel 4: Validate start and end date with before and after validation -
i want validate 2 date fields in form from_date , end_date. need check from_date less end_date.
$rules = array('from_date' => array('sometimes','date_format:"y-m-d"', 'before:'.input::get('to_date') ), 'to_date' => array('sometimes','date_format:"y-m-d"', 'after:'.input::get('from_date') ) );
this tried. not work. if give to_date empty value through error.
laravel 5:
here more extensive approach follows modern principles , more laravel-like. little more complex still easy follow , end results much cleaner.
let's start changing few things. let's cut down specific problem, utilize newer array syntax , apply formatting.
$rules = [ 'from_date' => [ 'before:'.input::get('to_date') // larn ], 'to_date' => [ 'after:'.input::get('from_date') // 1 on own ] ];
now let's create new request php artisan make:request storewhateverrequest
. create app/http/request/storewhateverrequest.php
file. open , place rules in homecoming array of rules()
function.
return [ 'from_date' => 'date', 'to_date' => 'date|after_field:from_date' ];
this not work yet because after_field
isn't available utilize yet. let's create that. need new class extends validator. can place in app/services
. need similar to:
<?php namespace app\services; utilize illuminate\validation\validator; utilize carbon\carbon; class afterfieldvalidator extends validator { public function validateafterfield($attribute, $value, $parameters) { homecoming carbon::parse($value) > carbon::parse($this->data[$parameters[0]]); } }
in above have: $attribute
name of field checking (to_date), $value
value of field checking , $parameters
parameters passed validator(from_date) seen in 'to_date' => 'date|afterfield:from_date'
. need other info fields passed validator, can these $this->data
. have preform logic appropriately. don't need carbon here sure parse string don't string comparison.
now need load application. set below code within boot()
function in app/providers/appserviceproviders.php
.
validator::resolver(function($translator, $data, $rules, $messages) { homecoming new afterfieldvalidator($translator, $data, $rules, $messages); });
the final step easiest. inject , instance of storewhateverrequest
our controller.
... public function store(storewhateverrequest $request) { ...
all done. sense pretty solid way solve problem.
php validation date laravel
No comments:
Post a Comment