【问题标题】:Laravel Form Request Array Validation Custom RulesLaravel 表单请求数组验证自定义规则
【发布时间】:2017-12-06 19:08:37
【问题描述】:

我想创建表单请求验证但不知道如何操作。

我有一个表格:

<form>
  <input type="text" name="fullname[0]">
  <input type="text" name="document_num[0]">

  <input type="text" name="fullname[1]">
  <input type="text" name="document_num[1]">

  <input type="text" name="fullname[2]">
  <input type="text" name="document_num[2]">

   .....

  <input type="text" name="fullname[n]">
  <input type="text" name="document_num[n]">

  <input type="submit">
</form>

表“用户”:

  id | fullname | document_num
  1  | John     | 111
  2  | Jane     | 112
 ..  | ...      | ...

当用户点击提交时,请求被发送到控制器方法,它首先由表单请求验证(或者它可以是常规验证器)。 所以我想写一个规则来检查:

for (i=0; i<numberOfUsersToAdd; i++)

    if  (‘document_num[$i]’ exists in ‘users’ in field ‘document_num’ ) {

       $user = Users::find(id of user in DB having this ‘document_num[$i]’) ; 

       check if (fullname[$i] == $user->fullname) {

                return true} // input-ed users name match his/her name in DB.

        else {return false}  // input-ed users name doesn't match his/her name in DB.

        } 

    else return true; // document_num[$i] doesn't exists in the database which's ok

if in words:检查表 users 中是否存在任何输入的 document_num[$i],如果是,则从 DB 中获取具有此 document_nubmer 的用户,并将他/她的全名值与输入中的全名 [$i] 进行比较.

怎么做?:)

感谢任何帮助!:)

【问题讨论】:

  • 你使用的是什么版本的 Laravel?
  • 嗨,罗斯! Laravel 5.4

标签: forms laravel validation


【解决方案1】:

好的。 YourFormRequest 中的验证逻辑如下:

  1. 让所有字段标记为必填,document_num 字段另外标记为整数。您可以添加其他额外的约束 - 没关系。
  2. YourFormRequestrules 方法中检查循环“给定document_num 的用户是否存在?”。
  3. 如果不存在,则可以 - 验证此字段成功。
  4. 如果存在,则检查“对于给定的fullname,用户全名是否等于。如果等于则确定 - 此字段的验证成功。否则,如果失败,则将始终失败的自定义规则附加到此字段。

让我们在一个工作示例中查看这种方法。

YourFormRequest.php

public function rules()
{
    $rules = [
        'fullname.*' => 'required',
        'document_num.*' => 'required|integer',
    ];

    $documentNums = request()->get('document_num');
    $fullnames = request()->get('fullname');

    for ($i = 0; $i < count($documentNums); $i++) {
        $user = User::where('document_num', $documentNums[$i])->first();
        if ($user && ($user->fullname != $fullnames[$i]) {
            $rules['document_num.' . $i] = "document_num_fail:$i"; //some rule that always fails. As argument we pass a row number of field that fails
        }
    }
    return $rules;
}

CustomValidator.php(例如放在 App\Services 文件夹中)

namespace App\Services;

class CustomValidator {

    public function documentNumFailValidate($attribute, $value, $parameters, $validator) {
        return false;
    }

    public function documentNumFailReplacer($message, $attribute, $rule, $parameters) {
        return str_replace([':index'], $parameters[0], $message);
    }
}

在这里您可以看到两个功能。首先 - 验证规则(我们总是通过 false 因为我们需要它)。其次 - 它只是错误消息的替代品。您想知道此错误在哪个字段行上(例如在第三行和字段上:分别为 fullname[2] 和 document_num[2])。正如我上面在附加失败规则的评论中所写,我们给出了验证方法失败的行数(documentNumFailReplacer 方法将用给定值替换错误消息中的占位符 :index)

下一步 - 在 AppServiceProvider.php 中注册此方法

public function boot()
{
    Validator::extend('document_num_fail',  'App\Services\CustomValidator@documentNumFailValidate');
    Validator::replacer('document_num_fail', 'App\Services\CustomValidator@documentNumFailReplacer');
}

最后一步 - 在 validation.php 中定义您的自定义消息

'custom' => [
        'document_num.*' => [
            'document_num_fail' => 'Input-ed user name doesn`t match his/her name in DB for specified :attribute (field position/number: :index)',
        ]
    ],

'attributes' => [
    'document_num.*' => 'document number',
],

【讨论】:

  • 天哪。现在要检查它。但无论如何你都很棒:) 有没有可能有你的任何联系人 - 我一直需要 Laravel 的一位伟大的顾问:)
  • ="document_num_fail:$i"; - 不应该是:=“document_num_fail:'.$i.'' 吗?
  • 不管“document_num_fail:.$i”或“document_num_fail:”。 $i 您的变体不正确。你只需要这样的结构:document_num_fail:4
  • 试试代码。你会看看是否有一些错误。
  • 试过了。它输出:“FatalThrowableError in Request.php line 727: Type error: Too little arguments to function Symfony\Component\HttpFoundation\Request::get(), 0 pass in /Users/sergeyfomin/code/first/app/Http/Requests /TestFormRequest.php 在第 32 行和至少 1 预期”和第 32 行是: $documentNums = request()->get()->get('document_num');
猜你喜欢
  • 2020-02-17
  • 1970-01-01
  • 2018-10-25
  • 2017-04-11
  • 2018-02-18
  • 2015-05-01
  • 2018-06-03
  • 2018-04-24
  • 2017-06-13
相关资源
最近更新 更多