Laravel表单请求数组验证自定义规则 [英] Laravel Form Request Array Validation Custom Rules

查看:515
本文介绍了Laravel表单请求数组验证自定义规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个表单请求验证,但不知道如何做.

I want to create a Form Request validation and don't know how-to.

我有一个表格:

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

当用户单击提交时,请求将被发送到控制器方法,该方法首先由Form Request(或可以是常规的Validator)进行验证. 所以我想写一个检查的规则:

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

如果用词表示:检查表用户中是否有任何输入的document_num [$ i],如果是,请从DB中获取具有此document_nubmer的用户,并将其全名值与输入中的全名[$ i]进行比较

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.

该怎么做?:)

感谢任何帮助!:)

推荐答案

好.接下来在YourFormRequest中进行此验证的逻辑:

Ok. Logic of this validation in YourFormRequest is next:

  1. 将所有字段标记为必填字段,并将document_num字段另外标记为整数.您可以添加其他附加约束-没关系.
  2. YourFormRequestrules方法中,检查循环是否存在给定document_num的用户?".
  3. 如果它不存在,那么确定-此字段的验证成功.
  4. 如果存在,则检查给定的fullname用户全名是否等于.如果等于,则确定-此字段的验证成功.否则,如果失败,则将始终失败的自定义规则附加到此字段.
  1. Let mark all fields as required and document_num field additionaly as integer. 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?".
  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.

让我们在实际的示例中了解这种方法.

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(例如,将其放在App \ Services文件夹中)

CustomValidator.php (place it for example in App\Services folder)

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);
    }
}

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

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

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

Next step - register this methods in 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中定义您的自定义消息

And final step - define your custom messages in 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表单请求数组验证自定义规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆