代码之家  ›  专栏  ›  技术社区  ›  Tim Lewis

Laravel验证日期格式m/y不接受特定值

  •  3
  • Tim Lewis  · 技术社区  · 6 年前

    我有下面的验证规则用于支付方法的基本验证(高级事物,如CVD验证,现有的卡等)在Moneris之后处理。

    $rules = [
        "type" => "required|in:visa,mastercard",
        "nickname" => "required",
        "credit_card_number" => "required|numeric|digits:16",
        "expiry" => "required|string|size:5|date_format:m/y|after:today",
        "cvd" => "required|numeric|digits:3"
    ];
    

    规则 expiry 不接受特定值, 04/yy ,但它正在接受 03/yy 05/yy 我不知道为什么会这样,但我需要补救。有人发现这种行为吗?

    作为参考,结果 dd($request->input(), $validator->passes(), $validator->errors()); 当我经过的时候 04/19 具体如下:

    array:6 [▼
      "type" => "visa"
      "nickname" => "Testing"
      "credit_card_number" => "4242424242424242"
      "expiry" => "04/19"
      "cvd" => "123"
      "masked_pan" => "************4242"
    ]
    false
    MessageBag {#502 ▼
      #messages: array:1 [▼
        "expiry" => array:1 [▼
          0 => "The expiry does not match the format m/y."
        ]
      ]
      #format: ":message"
    }
    

    当我发送 05/19 ,一切正常:

    array:6 [▼
      "type" => "visa"
      "nickname" => "Testing"
      "credit_card_number" => "4242424242424242"
      "expiry" => "05/19"
      "cvd" => "123"
      "masked_pan" => "************4242"
    ]
    true
    MessageBag {#502 ▼
      #messages: []
      #format: ":message"
    }
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Tim Lewis    6 年前

    看起来这是一个关于这个验证规则在Laravel 5.4中如何工作的问题。为了解决这个问题,我检查了输入的日期有效性 01/ ,如果它有效,则将其合并到请求中,并使用 endOfMonth() 处理 after:today 验证:

    $mergeDate = null;
    $rawInput = $request->input("expiry");
    try {
        $mergeDate = Carbon::createFromFormat("d/m/y", "01/".$request->input("expiry"))->endOfMonth();  
    } catch(\Exception $ex){}
    
    $request->merge([
        "masked_pan" => str_repeat("*", 12).substr($request->input("credit_card_number", ""), -4),
        "expiry" => $mergeDate ? $mergeDate->format("d/m/y") : $request->input("expiry")
    ]);
    

    所以现在,如果我通过 04/22 ,它将检查 01/04/22 有效,然后转换为月底 30/04/22 ,然后将其替换为传递给验证的值(该值也需要更新)

    "expiry" => "required|string|size:8|date_format:d/m/y|after:today",
    

    我还得更新和通过 $messages 为避免用户混淆:

    $messages = [
        "expiry.size" => "The :attribute filed must be 5 characters.",
        "expiry.date_format" => "The :attribute field does not match the format m/y"
    ];
    
    $validator = \Validator::make($request->all(), $rules, $messages);
    

    最后,如果有错误,用原始输入替换该值(这样用户就看不到他们没有输入的值)

    if(!$validator->passes()){
        $request->merge(["expiry" => $rawInput]);
        return back()->withErrors($validator)->withInput();
    }
    

    一派胡言,但似乎能应付 2012年4月 其他的约会也不错。