简体   繁体   English

Laravel表单请求数组验证自定义规则

[英]Laravel Form Request Array Validation Custom Rules

I want to create a Form Request validation and don't know how-to. 我想创建一个表单请求验证,但是不知道如何做。

I have a form: 我有一个表格:

<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>

table 'users': 表“用户”:

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

when user clicks submit a request is sent to controller method where it's first being validated by Form Request (or it can be a regular Validator). 当用户单击提交时,请求将被发送到控制器方法,该方法首先由Form Request进行验证(或者可以是常规的Validator)。 So I want to write a rule which checks: 所以我想写一个规则来检查:

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: check if any input-ed document_num[$i] exists in the table users, if yes, get the user having this document_nubmer from DB and compare his/her fullname value to fullname[$i] from input. 如果用词表示:检查表用户中是否有任何输入的document_num [$ i],如果是,请从DB中获取具有此document_nubmer的用户,并将其全名值与输入中的fullname [$ i]进行比较。

How to do it?:) 怎么做?:)

Appreciate any help!:) 感谢任何帮助!:)

Ok. 好。 Logic of this validation in YourFormRequest is next: YourFormRequestYourFormRequest中此验证的逻辑:

  1. Let mark all fields as required and document_num field additionaly as integer. 让所有字段标记为必填字段,并将document_num字段附加标记为整数。 You can add other additional constraints - it dont matter. 您可以添加其他附加约束-没关系。
  2. In rules method of YourFormRequest check in loop "is user exists for given document_num ?". YourFormRequest rules方法中,检查循环“给定document_num是否存在用户?”。
  3. If it not exists then ok - validation of this field is success. 如果不存在,则确定-此字段的验证成功。
  4. If it exists then check "is user fullname equals for given fullname . If equals then ok - validation of this field is success. Otherwise if it fails then attach to this field your custom rule that always fails. 如果存在,则检查“用户全名是否等于给定的fullname 。如果相等,则确定-此字段的验证成功。否则,如果失败,则将始终失败的自定义规则附加到此字段。

Let see this approach on a working example. 让我们在一个可行的例子上看看这种方法。

YourFormRequest.php 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 (place it for example in App\\Services folder) 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);
    }
}

Here you can see two functions. 在这里您可以看到两个功能。 First - to validate rule (we always pass false cause we need it). 首先-验证规则(我们总是传递错误的原因,因为我们需要它)。 Second - it just a replacer for error message. 其次-它只是错误消息的替代者。 You want to know on what field line was this error (for example on third line and fields: fullname[2] and document_num[2] respectively). 您想知道在哪个字段行出现此错误(例如,在第三行和字段上:分别为fullname [2]和document_num [2])。 As i wrote above in comment for attaching fail rule we give the number of row that fails to the validation method ( documentNumFailReplacer method will replace placeholder :index in error message with the given value) 正如我在上面的注释中所写的那样,附加失败规则的原因是验证方法失败的行数( documentNumFailReplacer方法将给定值替换错误消息中的占位符:index)

Next step - register this methods in AppServiceProvider.php 下一步-在AppServiceProvider.php中注册此方法

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

And final step - define your custom messages in validation.php 最后一步-在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',
],

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM