【问题标题】:Validating dates in Laravel (4.2)在 Laravel (4.2) 中验证日期
【发布时间】:2015-07-05 03:55:23
【问题描述】:

我在 Laravel (4.2) 中验证日期时遇到问题

$input = array('date_field' => '23/12/2');
$validation_rules = array('date_field'  => 'required|date_format:d/m/y');
$validation = Validator::make($input, $validation_rules);
echo ($validation->fails()) ? 'fail' : 'pass';

样本(虽然不正确)日期在 23/12/2 之后通过,验证器仍然返回通过,这在技术上应该是失败的。

我基本上是在尝试强制输入字段格式,使其与 dd/mm/yy UK 日期格式匹配。

谢谢!

【问题讨论】:

  • 因为您的日期字段值和验证格式相等,这就是它通过的原因。
  • 这是否被认为是正确的日期 -> 23/12/2 ??年份数字不应该至少是 2 位数字吗?

标签: php laravel


【解决方案1】:

除了date_format之外,您还可以使用regex:来保证格式,例如:

$validation_rules = [
    'date_field' => [
        'required',
        'date_format:m/d/y',
        'regex:#[0-9]{2}\/[0-9]{2}\/[0-9]{2}#'
    ]
];

但是'23/12/2' 是无效的,应该是失败的,但很困惑为什么它通过了,无论如何!

【讨论】:

  • 谢谢!添加正则表达式规则可确保日期格式为 xx/xx/xx。你仍然需要 date_format 规则,这样你就不能输入 99/99/99,它会单独通过正则表达式。
  • 实际上date_format 仍然是必需的 - 因为它是针对 PHP DateFormat 运行的 - 并且会检查日期本身是否 有效 - 即。你不能有 2 月 30 日等
【解决方案2】:

您可以在日期中使用 after 规则。您可以指定用户可以输入的最短日期。这样,如果用户在最小日期之后输入日期,则验证结果将通过。

例子

$input = array('date_field' => '23/12/2');
$minDate = '01/01/67';
$validation_rules = array('date_field'  => 'required|date_format:d/m/y|after:' . $minDate);
$validation = Validator::make($input, $validation_rules);
echo ($validation->fails()) ? 'fail' : 'pass';

另一种解决方案,您必须编写自定义验证来检查日期或月份用户输入的内容是否更多。

用于验证月份的自定义验证示例

Validator::extend('maxMonth', function($field,$value,$parameters){

    $value = explode("/", $value);
    if($value[1] < 13) {
        $value[1] = true;
    }
    else {
        $value[1] = false;
    }
    return $value[1];
});

Route::get('/date', function()
{

    $input = array('date_field' => '33/12/68');

    $validation_rules = array('date_field'  => 'required|date_format:d/m/y|maxMonth');

    $messages = array(
        'maxMonth'=>'Please enter month between 01-12'
    );

    $validation = Validator::make($input, $validation_rules, $messages);

    if($validation->passes()){
        // Do something if passes
    }else{
        // Do something if fails
    }
});

【讨论】:

  • 感谢您的回答。我不确定可能的日期范围是多少,所以无法指定 minDate。
猜你喜欢
  • 2021-03-17
  • 1970-01-01
  • 1970-01-01
  • 2018-05-21
  • 1970-01-01
  • 2018-10-29
  • 2018-08-04
  • 2022-01-24
  • 1970-01-01
相关资源
最近更新 更多