【问题标题】:How do I check for a specific error in Laravel 5.2 validation?如何检查 Laravel 5.2 验证中的特定错误?
【发布时间】:2017-11-08 07:32:15
【问题描述】:

现在,我可以使用以下方法检查刀片中存在验证错误的字段:

@if($errors->has('field_name'))
 <div class="help-block">
  Lorem Ipsum
 </div>
@endif

在我的控制器中,我使用 not_in 规则:

"field_name" =&gt; "required|string|not_in:

我想知道,我可以将 if 语句更改为仅检查 not_in 规则吗?

例子:

@if($errors-&gt;has('field_name.not_in'))

【问题讨论】:

  • 为什么要检查特定规则,如果要根据规则检查特定消息,则可以为特定规则设置消息
  • 是的,我有。但是,我需要在消息中添加一个锚标记,当我在自定义错误消息中放置一个锚标记时,它没有呈现 html。

标签: php laravel laravel-5 laravel-5.2


【解决方案1】:
@if($errors->has('field_name') and $errors->first('field_name') == 'The selected field_name is invalid.')
    this is just for not in validation for special input.
@endif

【讨论】:

    【解决方案2】:

    您可以使用 Laravel 的自定义错误消息来做到这一点。

    $messages = [
        'field.required' => 'required',
        'field.string' => 'string',
        'field.not_in' => 'not_in',
    ];
    

    然后通过执行以下操作;

    if($errors->has('field')){
        foreach($errors->get('field') as $error) {
            if($error == "not_in") {
                // do something
            }
        }
    }
    

    这是一个非常混乱的解决方案,但我似乎找不到 Laravel 提供的任何更漂亮的解决方案。我想问题是你为什么要这样做?可能有一种方法可以提供更优雅的解决方案,而不是使用错误包。

    【讨论】:

    • 我在消息中需要一个锚标记,当我在自定义错误消息中放置一个锚标记时,它没有呈现 html。
    猜你喜欢
    • 2016-03-28
    • 2017-07-01
    • 1970-01-01
    • 2016-05-28
    • 2017-01-20
    • 2023-04-01
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多