In my app, the user selects date from a datepicker and the date is then displayed in the input in a format that corresponds user's locale.
When the form is submitted, I would like to validate the respective date, however, the validator does not know the date format that the date was submitted in.
My question is whether I should mutate the date into Y-m-d before it is passed to validator or is there a way I can tell the Validator the right format to validate in?
The date in the date field has to be after today's date and not in the past. It also has to be within 30 days from today's date. So if today is 15/01/2013, then the form can only accept any date within 30 days after the 15/02/2013, so the 14/04/2007 plus 30 days!
Just create a new validation rule in laravel to validate the timestamp... Validator::extend('isTimeStamp', function($attribute, $value, $parameters) { return ((string) (int) $value === $value) && ($value <= PHP_INT_MAX) && ($value >= ~PHP_INT_MAX); }); You can now use isTimeStamp validation rule to validate timestamp.
The easier option is to use the Laravel date_format:format
rule (https://laravel.com/docs/5.5/validation#rule-date-format). It's a built-in function in Laravel without the need for a custom rule (available in Laravel 5.0+).
You can do:
$rule['date'] = 'required|date_format:d/m/Y';
or
$rule['date'] = 'required|date_format:Y-m-d';
Laravel Custom Validation Rules
You can define the multi-format date validation in your AppServiceProvider
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
Validator::extend('new-format', function($attribute, $value, $formats) {
foreach($formats as $format) {
$parsed = date_parse_from_format($format, $value);
// validation success
if ($parsed['error_count'] === 0 && $parsed['warning_count'] === 0) {
return true;
}
}
// validation failed
return false;
});
}
}
Now you can use custom validation rule:
'your-date' => 'new-format:"Y-m-d H:i:s.u","Y-m-d"'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With