Laravel Custom Validation of Two Dates - laravel

I'm creating a form in Laravel which has two fields: departure-date and return-date. I'm trying to create custom validation logic where the departure date entered MUST be on the same day or any other date after the user fills in the form. The return-date should also be after the departure date. Kindly assist?
Form Layout
<!-- Departure date-->
<div class="form-line registar2 love {{ $errors->has('departure_date') ? ' has-error' : '' }}">
<input type="date" class="form-input" name="departure_date" value="{{ old('departure_date') }}" required>
<label>Departure Date *</label>
<div class="error-label">Field is required!</div>
<div class="check-label"></div>
#if ($errors->has('departure_date'))
<span class="help-block">
<strong>{{ $errors->first('departure_date') }}</strong>
</span>
#endif
</div>
<!--End departure-->
<!-- Return date-->
<div class="form-line registar2 move {{ $errors->has('return_date') ? ' has-error' : '' }}">
<input type="date" class="form-input" name="return_date" value="{{ old('return_date') }}" required>
<label>Return Date *</label>
<div class="error-label">Field is required!</div>
<div class="check-label"></div>
#if ($errors->has('return_date'))
<span class="help-block">
<strong>{{ $errors->first('return_date') }}</strong>
</span>
#endif
</div>
<!-- End return date-->
Validation in Controller
public function validatePlanEntries(Request $request)
{
$validation = $this->validate($request, [
'departure_date' => 'required',
'return_date' => 'required'
]
);
}

public function validatePlanEntries(Request $request)
{
$validation = $this->validate($request, [
'departure_date' => 'required|date|after:now',
'return_date' => 'required|date|after:departure_date',
]
);
}
FYI: the after:xxxxx rule either compares to another input field or respects the rules of the native DateTime PHP class. So you may enter after:now +2 hours.
To override the messages and write your own, create a messages() function like this:
public function messages()
{
return [
'departure_date.required' => 'Departure date is required',
'departure_date.after' => 'Please choose a date in the future',
'return_date.required' => 'Return date is required',
'return_date.after' => 'Your return date is before departure'
];
}
Just in case you are looking for a jquery solution to make datepicking more user friendly and less error bound, you may have a look at Bootstrap Datepicker, it's probably worth the effort. Good luck on your project!

Related

No error message shown when validating array input field using Laravel 7

No errors shown. Doesn't matter what I put in input field.
Here is my blade file.
<input type="text" class="form-control" name="names[]"/>
#if($errors->has('names'))
<span class="invalid-feedback d-block" role="alert">
<strong>{{ $errors->first('names') }}</strong>
</span>
#endif
Here is my controller.
public function store(Request $request)
{
$request->validate([
'names.*' => 'required|exists:users,name',
]);
}
we need to validate names as array first then we can validate each attribute which is inside array.
$request->validate([
'names' => 'required|array',
'names.*' =>'required|exists:users,name'
]);
You may use like this. I used this type of my own.
<div class="{{'form-group required'.$errors->first('title',' has-error')}}">
<label>Title</label>
<input type="text" name="title[]" class="form-control" required>
<div class="text-danger">{{$errors->has('title') ? $errors->first('title') : ''}}</div>
</div>
IN my controller I use like this.
$request->validate([
'title' => ['required','array'],
'title.*' => ['required','unique:galleries','min:5'],
]);
And it gives me the error like this
The title must be a string.
The title must be at least 5 characters.

laravel custom login error validation

I'm doing multi authentication in Laravel in user login form the error validation is working but in my company login form the error validation is not working . please help me I'm just new in Laravel and I'm just a student. Sorry for my English
this is my code in login
public function login(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required'
]);
if (Auth::guard('company')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember)) {
return redirect()->intended(route('company'));
}
return redirect()->back()->withInput($request->only('email','remember'));
}
and this is my form where error must show
<div class="form-group row">
<label for="email" class="col-sm-4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control{{ $errors->has('email') ? ' is-invalid' : '' }}" name="email" value="{{ old('email') }}" required autofocus>
#if ($errors->has('email'))
<span class="invalid-feedback">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
</div>
instead of:
return redirect()->back()->withInput($request->only('email','remember'));
use this:
$errors = new MessageBag(['password' => ['Email and/or password invalid.']]);
return Redirect::back()->withErrors($errors)->withInput(Input::except('password'));
also add this to the top of your controller
use Redirect;
use Illuminate\Support\MessageBag;
use Illuminate\Support\Facades\Input;

How to validate this context? In the validate method()?

Context: When a user creates a new conference he needs to select a start and an end date for the conference and the user needs to enter an end date after the start date, that is, the end date needs to be after the start date.
To deal with this logic properly, do you know if we can use the laravel validate method in the store method or is not a good approach or not possible do with this method? If it is not adequate to do this in the validate method do you know how to properly do that?
ConferenceController store method:
public function store(Request $request)
{
$this->validate($request, [
'conference_name' => 'required|max:255|string',
'conference_startDate' => 'required|date_format:d/m/Y',
'conference_endDate' => 'required|date_format:d/m/Y',
]);
$conference = Conference::create([
'nome' => $request->conference_name,
'startDate' => Carbon::parse($request->conference_startDate),
'endDate' => Carbon::parse($request->conference_endDate),
]);
}
Html fields:
<div class="form-row">
<div class="form-group col-md-6">
<label for="conference_startDate">Stard Date</label>
<div class="input-group date" data-provide="datepicker">
<input type='text' onkeydown="event.preventDefault()"
name="conference_startDate" value="{{ old('conference_startDate') }}"
class="form-control" placeholder="DD/MM/YYY" />
<span class="input-group-addon"><i class="fa fa-calendar text-primary" aria-hidden="true"></i></span>
</div>
</div>
<div class="form-group col-md-6">
<label for="conference_endDate">End Date</label>
<div class="input-group date" data-provide="datepicker">
<input type='text' class="form-control"
value="{{ old('conference_endDate') }}" name="conference_endDate" placeholder="DD/MM/YYY"/>
<span class="input-group-addon"><i class="fa fa-calendar text-primary" aria-hidden="true"></i></span>
</div>
</div>
</div>
As stated in the documentation, you could use the after rule:
after:date
The field under validation must be a value after a given date. The
dates will be passed into the strtotime PHP function:
'start_date' => 'required|date|after:tomorrow'
Instead of passing a
date string to be evaluated by strtotime, you may specify another
field to compare against the date:
'finish_date' => 'required|date|after:start_date'
So in your code:
$this->validate($request, [
'conference_name' => 'required|max:255|string',
'conference_startDate' => 'required|date_format:d/m/Y',
'conference_endDate' => 'required|date_format:d/m/Y|after:conference_startDate',
]);
Also, check this similar question.
Update
To check for a date after of equal another date, as stated in the docs, you should use:
after_or_equal:date
The field under validation must be a value after
or equal to the given date. For more information, see the after rule.

Laravel - How to handle errors on PUT form?

I am working with laravel 5.2 and want to validate some data in an edit form. I goal should be to display the errors and keep the wrong data in the input fields.
My issue is that the input is validated by ContentRequest and the FormRequest returns
$this->redirector->to($this->getRedirectUrl())
->withInput($this->except($this->dontFlash))
->withErrors($errors, $this->errorBag);
which is fine so far. Next step the edit action in the controller is called and all parameters are overwritten.
What I have currently done:
ContentController:
public function edit($id)
{
$content = Content::find($id);
return view('contents.edit', ['content' => $content]);
}
public function update(ContentRequest $request, $id)
{
$content = Content::find($id);
foreach (array_keys(array_except($this->fields, ['content'])) as $field) {
$content->$field = $request->get($field);
}
$content->save();
return redirect(URL::route('manage.contents.edit', array('content' => $content->id)))
->withSuccess("Changes saved.");
}
ContentRequest:
class ContentRequest extends Request
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'title' => 'required|min:3',
'body' => 'required|min:3'
];
}
}
How can I fix this? The form looks like this:
<form action="{!! URL::route('manage.contents.update', array('content' => $content->slug)) !!}"
id="site-form" class="form-horizontal" method="POST">
{!! method_field('PUT') !!}
{!! csrf_field() !!}
<div class="form-group {{ $errors->has('title') ? 'has-error' : '' }}">
<label for="title" class="col-sm-2 control-label">Title</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="title" id="title" placeholder="Title"
value="{{ $content->title }}">
#if ($errors->has('title'))
<span class="help-block">
<strong>{{ $errors->first('title') }}</strong>
</span>
#endif
</div>
</div>
</form>
Try something like the following:
<input
type="text"
class="form-control"
name="title"
id="title"
placeholder="Title"
value="{{ old('title', $content->title) }}" />
Note the value attribute. Also check the documentation and find Retrieving Old Data.

How to use custom validation attributes on an array of inputs

I'm using Laravel to build a form that contains an array of inputs and I’m having difficulty in showing the translated attribute name when a validation error occurs. For simplicity sake I will post a simple example of my problem.
Form inside the view:
<form method="POST" action="{{ route('photo.store') }}" accept-charset="UTF-8" role="form">
<input name="_token" type="hidden" value="{{ csrf_token() }}">
<div class="row">
<div class="col-lg-12">
<div class="form-group{{ $errors->has('testfield') ? ' has-error' : '' }}">
<label class="control-label"
for="testfield">{{ trans('validation.attributes.testfield') }}</label>
<input class="form-control" name="testfield" type="text" id="testfield"
value="{{ old('testfield') }}">
#if ($errors->has('testfield'))
<p class="help-block">{{ $errors->first('testfield') }}</p>
#endif
</div>
</div>
<div class="col-lg-12">
<div class="form-group{{ $errors->has('testfieldarray.0') ? ' has-error' : '' }}">
<label class="control-label"
for="testfieldarray-0">{{ trans('validation.attributes.testfieldarray') }}</label>
<input class="form-control" name="testfieldarray[]" type="text" id="testfieldarray-0"
value="{{ old('testfieldarray.0') }}">
#if ($errors->has('testfieldarray.0'))
<p class="help-block">{{ $errors->first('testfieldarray.0') }}</p>
#endif
</div>
</div>
<div class="col-lg-12">
<div class="form-group{{ $errors->has('testfieldarray.1') ? ' has-error' : '' }}">
<label class="control-label"
for="testfieldarray-1">{{ trans('validation.attributes.testfieldarray') }}</label>
<input class="form-control" name="testfieldarray[]" type="text" id="testfieldarray-1"
value="{{ old('testfieldarray.1') }}">
#if ($errors->has('testfieldarray.1'))
<p class="help-block">{{ $errors->first('testfieldarray.1') }}</p>
#endif
</div>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<input class="btn btn-primary" type="submit" value="Gravar">
</div>
</div>
Rules function in the form request:
public function rules() {
$rules = [
'testfield' => array('required'),
];
foreach ($this->request->get('testfieldarray') as $key => $val) {
$rules['testfieldarray.' . $key] = array('required');
}
return $rules;
}
lang/en/validation.php
'attributes' => [
'testfield' => 'Test Field',
'testfieldarray' => 'Test Field Array',
],
The validation is performed correctly, as do the error messages. The only problem in the error messages is the name of the attribute displayed. In both array inputs, the attribute name inserted in the message is 'testfieldarray.0' and 'testfieldarray.1' instead of 'Test Field Array'. I already tried to add on the language file 'testfieldarray.0' => 'Test Field Array', 'testfieldarray.1' => 'Test Field Array', but the messages remain unchanged. Is there a way to pass the attribute names correctly?
Just see the example to add custom rules for integer type value check of array
Open the file
/resources/lang/en/validation.php
Then add the custom message.
// add it before "accepted" message.
'numericarray' => 'The :attribute must be numeric array value.',
Again Open another file to add custom validation rules.
/app/Providers/AppServiceProvider.php
So, add the custom validation code in the boot function.
public function boot()
{
$this->app['validator']->extend('numericarray', function ($attribute, $value, $parameters)
{
foreach ($value as $v) {
if (!is_int($v)) {
return false;
}
}
return true;
});
}
Now you can use the numericarray for integer type value check of array.
$this->validate($request, [
'input_filed_1' => 'required',
'input_filed_2' => 'numericarray'
]);
----------- Best of Luck --------------
1-if you split the validation in file request then add the method attributes and set the value of each key like this :
public function attributes()
{
return [
'name'=>'title',
];
}
2- but if don't split the validation of the request then you just need to make variable attributes and pass the value of items like this :
$rules = [
'account_number' => ['required','digits:10','max:10','unique:bank_details']
];
$messages = [];
$attributes = [
'account_number' => 'Mobile number',
];
$request->validate($rules,$messages,$attributes);
// OR
$validator = Validator::make($request->all(), $rules, $messages, $attributes);
Use custom error messages inside your parent method....
public function <metod>(Request $request) {
$rules = [
'testfield' => 'required'
];
$messages = [];
foreach ($request->input('testfieldarray') as $key => $val) {
$rules['testfieldarray.' . $key] = 'required';
$messages['testfieldarray.' . $key . '.required'] = 'Test field '.$key.' is required';
}
$validator = Validator::make($request->all(), $rules,$messages);
if ($validator->fails()) {
$request->flash();
return redirect()
->back()
->withInput()
->withErrors($validator);
}
}
}

Resources