且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么我的验证规则在Laravel Controller中不起作用?

更新时间:2022-05-30 04:40:07

好吧,我最终编写了一个自定义规则.我认为这不是正确的解决方案,尽管考虑到Laravel具有方便的内置功能.我觉得我应该利用它.就我而言,我正在处理停电日期.

Well, I ended up writing a custom rule. I don't think this is the correct solution though given that Laravel has the handy built-in stuff. I feel like I should be leveraging that instead. In my case I am working with Blackout date(s).

她就是我最终的目标.如果有办法使内置方法起作用,请告诉我,以便我更新答案.

Hers is what I ended up with. If there is a way to make the built-in methods work, please let me know so I can update the answer.

MyTest.php

/** @test */
public function a_blackout_date_must_be_formatted_correctly()
{
    $blackout = factory(Blackout::class)->raw([
        'date' => date('d/m/Y'),
    ]);

    $response = $this->postJson('api/v1/blackouts', $blackout)
        ->assertStatus(422)
        ->assertJsonValidationErrors('date');
}

MyController.php

public function store(Request $request)
{
    $attributes = $request->validate([
        'date' => ['required', new DateFormatRule],
        ...
    ]);

    $blackout = new Blackout($attributes);

    ...

}

DateFormatRule.php

public function passes($attribute, $value)
{
    // The format we're looking for.
    $format = 'Y-m-d';

    // Create a new DateTime object.
    $date = DateTime::createFromFormat($format, $value);

    // Verify that the date provided is formatted correctly.
    return $date && $date->format($format) === $value;
}

/**
 * Get the validation error message.
 *
 * @return string
 */
public function message()
{
    return 'Invalid date format.';
}

在我的测试中,我得到了预期的 422 响应.我可以通过将预期错误的名称从 date 更改为 date123 来验证一切是否正常,然后我会得到一个错误-说它正在期待 date 不是 date123 .

In my test I am getting a 422 response as expected. I can verify things are working by changing the name of the expected error from date to date123 and I'll get an error -- saying It was expecting date not date123.

希望这对某人有帮助!