When I submit a form, this is what I do to validate my fields...
<?php
$this->validate($request, [
'name' => __('required|max:255|unique:templates,name,NULL,id,company_id,:company_id', [
'company_id' => $request->input('companies')
]),
'modules' => 'required|numeric',
'companies' => 'required|numeric',
'start_date' => 'required_with:limited_availability|date|before:end_date',
'end_date' => 'required_with:limited_availability|date|after:start_date',
'indesign_location' => __('required|file|mimetypes:application/zip|max::max_upload_size', [
'max_upload_size' => config('file.max_size')
])
]);
What I want to achieve:
The fields start_date
and end_date
should only be required (and therefore be validated) when the field limited_availability
is present.
What happens now: I don't get the message that the field is required, but I do get an error message on both date fields that the specified date is invalid.
The limited_availability
is a checkbox and both start_date
and end_date
are date input fields.
How can I fix this problem?
May be this is a naive solution. But I am pretty sure this will works.
// First thing we separate the validation rule and save it in a variable
$rules = [
'name' => __( 'required|max:255|unique:templates,name,NULL,id,company_id,:company_id', [
'company_id' => $request->input( 'companies' )
] ),
'modules' => 'required|numeric',
'companies' => 'required|numeric',
'indesign_location' => __( 'required|file|mimetypes:application/zip|max::max_upload_size', [
'max_upload_size' => config( 'file.max_size' )
] )
];
// the solution is here
if ($request->has('limited_availability')) {
$rules['start_date'] = 'required|date|before:end_date';
$rules['end_date'] = 'require|date|after:start_date';
}
$this->validate( $request, $rules);
Hope it helps.