问题
A simple date format mm/dd/yyyy validation is all I need...
$rules = array(
'renewal_date' => array('required', 'date_format:?')
);
What do I set the date format to? The Laravel documentation could be so much better.
回答1:
Documentation is pretty clear to me, you should use
date_format:format
"The field under validation must match the format defined according to the date_parse_from_format PHP function."
Looking at it: http://php.net/manual/en/function.date-parse-from-format.php, I see you can do something like this:
$rules = array(
'renewal_date' => array('required', 'date_format:"m/d/Y"')
);
This is pure PHP test for it:
print_r(date_parse_from_format("m/d/Y", "04/01/2013"));
You can also do it manually in Laravel to test:
$v = Validator::make(['date' => '09/26/13'], ['date' => 'date_format:"m/d/Y"']);
var_dump( $v->passes() );
To me it's printing
boolean true
回答2:
I got a similar problem, but with a d/m/Y date format. In my case, the problem was that I defined both "date" and "date_format" rules for the same field:
public static $rules = array(
'birthday' => 'required|date|date_format:"d/m/Y"',
...
The solution is to remove the "date" validator: you must not use both. Like this:
public static $rules = array(
'birthday' => 'required|date_format:"d/m/Y"',
...
after that, all is well.
回答3:
Workaround:
'renewal_date' => array('required', 'date_format:m/d/Y', 'regex:/[0-9]{2}\/[0-9]{2}\/[0-9]{4}/')
回答4:
You should use with double quote
like "Y-m-d H:i:s"
$rules = array(
'renewal_date' => array('required', 'date_format:"m/d/Y"')
^ ^ this ones
);
Discussion about this issue on GitHub: https://github.com/laravel/laravel/pull/1192
回答5:
date_format didn't work for me , so I did this custom validation
Validator::extend('customdate', function($attribute, $value, $parameters) {
$parsed_date = date_parse_from_format ( "Y-m-d" , $value);
$year = $parsed_date['year'];
$month = $parsed_date['month'];
$month = $month <= 9 ? "0" . $month : $month;
$day = $parsed_date['day'];
$day = $day <= 9 ? "0" . $day : $day;
return checkdate($month, $day, $year);
});
$validation = Validator::make(
array('date' => $num),
array('date' => 'customdate')
);
回答6:
Use the PHP date_parse_from_format
(Laravel 4):
'birthday' => 'date_format:m/d/Y'
Your validation message will also use "m/d/Y"
which the average user will not understand.
The birthday does not match the format m/d/Y
Recommend customizing your message for this invalid response. The birthday does not match the format mm/dd/yyyy
回答7:
Source : Click Here
You can use like
$rules = [
'start_date' => 'date_format:d/m/Y|after:tomorrow',
'end_date' => 'date_format:d/m/Y|after:start_date',
];
来源:https://stackoverflow.com/questions/18852536/laravel-4-validation-is-broken