0
我有4個輸入,其中有我的表單中的日期,我想在提交表單之前創建所有這些日期的驗證。 這是我DatetimeHelper.php在laravel中創建日期驗證函數?
class DateTimeHelper
{
//This formats a date for insertion into the database
public static function FormatForDB($date, $format = "m/d/Y", $if_null = "0000-00-00", $outputFormat = "date")
{
if (!isset($date)) {
return $if_null;
}
if (trim($date) == "") {
return $if_null;
}
if (trim($date) == "0000-00-00" || trim($date) == "00-00-0000") {
return $if_null;
}
//var_dump(Carbon::createFromFormat($format, $date));die;
try{
$parsedDate = Carbon::createFromFormat($format, $date);
if ($outputFormat == 'date') {
return $parsedDate->toDateString();
} else if ($outputFormat == 'datetime') {
return $parsedDate->toDateTimeString();
} else if ($outputFormat == 'time') {
return $parsedDate->toTimeString();
}
}catch(\Exception $e){
return $if_null;
}
}
//This formats the return date from the database
public static function FormatFromDB($date, $format = "m/d/Y", $if_null = "0000-00-00")
{
if (!isset($date)) {
return $if_null;
}
if (trim($date) == "") {
return $if_null;
}
if (trim($date) == "0000-00-00" || trim($date) == "00-00-0000") {
return $if_null;
}
return Carbon::createFromFormat("Y-m-d", $date)->format($format);
}
}
這是我Validator.php
public static function validate_date($date, $format = DATE_ATOM)
{
try{
$parsedDate = Carbon::createFromFormat($format, $date);
return true;
}catch(\Exception $e){
return false;
}
}
我Controller.php這樣
$invalid_fields = [];
$events_fields =['date_1' => 'date1',
'date_2' => 'date2',
'date_3' => 'date3',
'date_4' => 'date4'];
function input_validate($request)
{
foreach ($request->all() as $key => $value) {
switch ($key) {
case 'date1':
if (!$this->validate_date($value)) {
$this->invalid_fields[] = $this->event_fields[$key].' is not a valid date';
}
break;}
case 'date2':
if (!$this->validate_date($value)) {
$this->invalid_fields[] = $this->event_fields[$key].' is not a valid date';
}
break;}
這種做法似乎根本不工作。任何幫助,將不勝感激。我在我的所有控制器中使用validate_date函數來驗證輸入