Date validation in laravel 5 - php

I have a StartDate field and a EndDate field. Both may start today or in the future. It is possible to have them both start on the same day, including today.
I have to make a validation for these.
What I've done so far is this:
'StartDate'=>'required|date_format:Y/m/d|after:yesterday',
'EndDate' => 'date_format:Y/m/d|after:yesterday',
What I don't know how to do is to validate true if both dates are equal as a second condition.
Anyone can help me, please ?

This is how you can validate date:
'start_date' => 'required|date',
'end_date' => 'required|date|after_or_equal:start_date'

EDIT
This was a solution up to Laravel 5.3. With Laravel 5.4, a rule after_or_equal was introduced
https://laravel.com/docs/5.4/validation#rule-after-or-equal
I had the same need for my web app. I solved it by creating a custom Request with the following rules method :
public function rules()
{
$rules = [
'start_date' => 'date_format:Y-m-d|after:today'
];
if ($this->request->has('start_date') && $this->request->get('start_date') != $this->request->get('end_date')) {
$rules['end_date'] = 'date_format:Y-m-d|after:start_date';
} else {
$rules['end_date'] = 'date_format:Y-m-d|after:today';
}
return $rules;
}

As per my understand I try to prepare custom validation rule which could help you to meet your requirement.
Current below mentioned rule only check if a start date is before end date.
<?php
namespace App\Providers;
use Validator;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider{
public function boot(){
Validator::extend('date_after', function($attribute, $value, $parameters) {
return strtotime( $value ) > strtotime( $this->attributes[ $parameters[0] ] );
});
Validator::extend('date_equal', function($attribute, $value, $parameters) {
return strtotime( $value ) == strtotime( $this->attributes[ $parameters[0] ] );
});
}
}
?>
Usage:
<?php
$inputs = array(
'start_date' => '2013-01-20',
'end_date' => '2013-01-15'
);
$rules = array(
'start_date' => 'required',
'end_date' => 'required|date_after:start_date'
);
$messages = array(
'date_after' => ":attribute must be date after Start Date."
);
$validation = Validator::make($inputs, $rules, $messages);
if( $validation->fails() )
{
echo '<pre>';
print_r($validation->errors);
echo '</pre>';
}
?>
However I did not test that code with my env... but I believe its help you much to meet requirement.
Please let me know your further requirement so I can provide specifically solution to your requirement.

Related

Laravel validation form request doesn't work for conditions rule with a date field

I have a problem with the form request validation rules. I need to check additional data when the input date is less than 18 years ago (the user is not an adult). I write rules but it doesn't work. This is my code:
$adultDate = Carbon::now()->subYears(18)->format('Y-m-d');
$rules = [
"brith_date" => 'required|date',
"patron_name" => "required_if:brith_date,after,".$adultDate."|string"
];
return $rules;
you can use Rule::when($condition, $rules)
<?php
use Illuminate\Validation\Rule;
public function rules()
{
$adultDate = Carbon::now()->subYears(18);
$condition=Carbon::parse($this->brith_date)->isAfter($adultDate);
return [
'brith_date' => ['required','date'],
'patron_name' => ['required' ,
Rule::when($condition, ['string']),
];
}

Laravel 5.2 validation: date_format:Y.m.d not working

I try to validate a POST request.
The format is: d.m.Y (12.1.2017)
My rule is required|date_format:d.m.Y for this field.
I get this error message:
InvalidArgumentException in Carbon.php line 425:
Unexpected data found.
Unexpected data found.
Data missing
If I change the . to - or even / it is working -> POST data changed before to match the rule.
I need the German format for this.
edit:
My validation rules:
public function rules()
{
return [
'title' => 'required|max:255',
'expiration_date' => 'required|date_format:d.m.Y',
//'description' => 'required',
'provision_agent' => 'required|integer|between:0,100',
'discount_consumer' => 'required|integer|between:0,100',
'quota' => 'required|integer',
];
}
Wrap your Format should work i just tried with 5.2 it's working fine.
public function rules()
{
return [
'title' => 'required|max:255',
'expiration_date' => 'required|date_format:"d.m.Y"',
//'description' => 'required',
'provision_agent' => 'required|integer|between:0,100',
'discount_consumer' => 'required|integer|between:0,100',
'quota' => 'required|integer',
];
}
But the error what you added in question InvalidArgumentException in Carbon.php line 425: it seems something else my guess you are using expiration_date some where in controller or model like this with Carbon
echo Carbon::createFromFormat('Y-m-d', '12.1.2017');
You should try something like this
echo Carbon::parse('12.1.2017')->format('Y-m-d')
Wrap your format into quotes:
'date_format:"d.m.Y"'
Try like this,
public function rules()
{
return [
'title' => 'required|max:255',
'expiration_date' => 'date_format:"d.m.Y"|required', // I have changed order of validation
//'description' => 'required',
'provision_agent' => 'required|integer|between:0,100',
'discount_consumer' => 'required|integer|between:0,100',
'quota' => 'required|integer',
];
}
Hope this will solve your problem.
If you don't succeed solving the issue otherwise, you can still use a custom validation rule:
Validator::extend('date_dmY', function ($attribute, $value) {
$format = 'd.m.Y';
$date = DateTime::createFromFormat($format, $value);
return $date && $date->format($format) === $value;
}, 'optional error message');
The extra check $date->format($format) === $value is to avoid erroneously accepting out-of-range dates, e.g. "32.01.2017". See this comment on php.net.
Once the custom validation rule has been defined, you can use it like so:
public function rules() {
return [
'expiration_date' => 'required|date_dmY',
];
}

custom error message for age validation in a form.(laravel)

I am building a form in which user must be of age 18 years or above.I have tried some methods but didn't worked.
in my controller:
$this->validate($request,[
'birthday' => 'required|date|before:-18 years',
]);
in request.php:(searched over internet)
abstract class Request extends FormRequest
{
public function messages()
{
return [
'birthday.before' => 'You must be 18 years old or above',
];
}
}
Actually, I don't clearly about your question.
If you want custom message of before validate, please go to resources/lang/en/validation.php and change it at
'custom' => [
'attribute-name' => [
'rule-name' => 'custom-message',
],
],
Hope it help!
You can compute the age from the date, then validate it as a number.
or you can validate a date, which is 18 years before now
$dt = new Carbon\Carbon();
$before = $dt->subYears(18)->format('Y-m-d');
$rules = [
'dob' => 'required|date|before:' . $before
];
or you can extend the validate and make custom one like in this answer : Check user's age with laravel validation rules
Hi to get your validation errors store your validator inside a variable
then just use $validator->errors() to get its errors
$validator = Model::validate($request,[
'birthday' => 'required|date|before:-18 years',
]);
$errors = $validator->errors();
echo "You error in birthday: ".$errors->get('birthday')[0];

Use sometimes() function in Laravel 5 request class

In laravel 4, I used the sometimes() method as below:
$validator = \Validator::make(
\Input::all(),
array(
'name' => array('required'),
'recurrence' => array('required_if:recurring,on'),
)
);
$validator->sometimes('recurrence', 'integer|min:1', function($input) {
return $input->recurring == 'on';
});
Notice integer|min:1 are applied to recurring only if recurrence is presented.
In laravel 5, I tried to implement the validation as a request class:
class CreateProductRequest extends Request {
public function authorize(){
return true;
}
public function rules(){
return [
'name' => array('required'),
'recurrence' => array('required_if:recurring,on'),
];
}
}
Looks like from a request class I am unable to call sometimes() method. The idea is to avoid validation code at controller.
Ok, I have emulated the behaviour expected using a custom condition without be 100% sure weather is the best practice:
$rules = [
'name' => array('required'),
'recurrence' => array('required_if:recurring,on'),
];
if ($this->has('recurring')){
$rules['recurrence'] = $rules['recurrence'] + ['integer', 'min:1'];
}
return $rules;

Laravel use Hash as Validator

i'm using Hash::check() to check current password with entered password. i use this if for check this action
$HashPassowrd = Hash::make(Input::get('password'));
if( ! Hash::check( Input::get('currPassword') , $data->password ) )
{
return Redirect::to('profile.update')
->withErrors('Current Password in Incorrect!');
}
how to use that as validator ? for example in this rules
$rules = array(
'name' => 'required|alpha',
'family' => 'required',
'email' => 'required|email',
'currPassword'=> 'required',
'password' => 'required|confirmed',
'password_confirmation'=>'required',
);
You can add custom rule in to the validator:
Validator::extend('checkHashedPass', function($attribute, $value, $parameters)
{
if( ! Hash::check( $value , $parameters[0] ) )
{
return false;
}
return true;
});
Now you can use this custom rule as:
'currPassword' => 'required|checkHashedPass:' . Input::get('currPassword')
So, if the validation fails for this rule then you'll get error messages for this in your view and can access using $errors->first('currPassword'); but you need to pass a custom error message for this custom rule you've created using:
$messages = array( 'currPassword.checkHashedPass' => 'Current Password failed!' );
So, during validation you have to pass the $messages array using:
$validator = Validator::make(Input::all(), $rules, $messages);
Check custom validation rules on the documentation.
You also can use a closure validation rule:
[
'currPassword' => function ($attribute, $value, $fail) {
if (! Hash::check($value, $this->user()->password)) {
$fail('Your current password doesnt match');
}
},
'password' => 'required|min:6|confirmed',
];
Since Laravel 6.x a password validation rule is added that will do the above for you.
Check its documentation
simply add this rule to your validation rules :
'password' => 'password:api'
where api is the authentication guard

Categories