in my laravel application i have an input field to insert date of birth,
my date format has to be d/m/y
and my age limit has to be 18-70
inside my controller's store
method I have following validation rule for the dob.
'date_of_birth'=>['required','bail','date','date_format:d/m/y',function ($attribute, $value, $fail) {
$age=Carbon::createFromFormat('d/m/y', $value)->diff(Carbon::now())->y;
if($age<18||$age>70){
$fail('Âge invalide. l\'âge devrait être 18-70');
}
},]
but every time when I try to submit the form with a correct date like 23/12/1995
it kept saying date format is invalid
CodePudding user response:
you have two problems with your code:
1- you should remove 'date' from validation, since you are passing a string not a date.
2- you should correct the format to be right: 'd/m/Y' Y is capital letter.
$rules = ['date_of_birth' => ['required', 'bail', 'date_format:d/m/Y',
function ($attribute, $value, $fail) {
$age = Carbon::createFromFormat('d/m/Y', $value)->diff(Carbon::now())->y;
if ($age < 18 || $age > 70) {
$fail('Âge invalide. l\'âge devrait être 18-70');
}
},
]];
CodePudding user response:
Use format
method in function
$age=Carbon::createFromFormat('d/m/y', $value)->diff(Carbon::now())->format('%y');