【问题标题】:how to use laravel's validation rule in custom validation rule?如何在自定义验证规则中使用 laravel 的验证规则?
【发布时间】:2017-12-01 06:42:49
【问题描述】:

我输入了$data =['identifier' = 'xxxxxxxxxx'];,并想将encrypt($data['identifier']) 保存到表infoid 列中。

我必须在保存之前进行验证。规则unique:info, id 不适合这里,所以我想写一个自定义的验证规则。而在自定义验证规则中,我先encrypt()取值,再使用unique验证规则。

我知道如何编写自定义验证规则,但如何在自定义验证规则中使用unique 验证规则?

【问题讨论】:

  • @ceejayoz 请详细阅读我的问题。在这里,我不是在编写自定义验证规则。我想扩展唯一规则。
  • id的初始值是多少?难道int会被加密?!
  • 换句话说,“扩展唯一规则”是什么意思?独一无二就是独一无二!即它会检查您的表格是否具有完全相同的值!
  • @KrisRoofe 你说“扩展唯一规则”。我说这是一个自定义验证规则。 unique 规则只是一个验证规则 - 您可以根据您的特定要求创建自己的规则来模仿它。

标签: php laravel validation input


【解决方案1】:

假设你有一个 ModuleRequest 来验证你的输入,你可以在这个类中编写这个方法

protected function validationData() 
{
    $all = parent::validationData();
    $all['email'] = encrypt($all['email']);
    return $all;

}

【讨论】:

  • 我知道这行得通。我想在我的问题中所述的验证规则中使用这个encrypt()
【解决方案2】:

规则“唯一”和“存在”使用 DatabasePresenceVerifier 类。因此,您不需要真正扩展唯一规则,只需访问此存在验证器即可。例如:

Validator::extend('encrypted_unique', function ($attribute, $value, $parameters, $validator) {
    list ($table, $column, $ignore_id) = $parameters; // or hard-coded if fixed
    $count = $validator->getPresenceVerifier()->getCount($table, $column, encrypt($value), $ignore_id);
    return $count === 0;
});

那你就可以照常使用了:

'identifier' => "encrypted_unique:table,column,$this_id"

【讨论】:

    【解决方案3】:

    Laravel 有自定义验证规则 (https://laravel.com/docs/8.x/validation#using-rule-objects) 例如,我有一个名为 clients 的表,它有两个使用 Laravel 的加密服务 (https://laravel.com/docs/8.x/encryption) 的唯一字段 ecnrypt,并且由于它已加密,我无法应用验证方法的唯一指令 (https://laravel.com/docs/8.x/validation#rule-unique)。字段是 code_clientemail

    这就是实施自定义验证规则的原因。 此 Service 有两种方法:passesmessage。方法passes 接受两个变量:$attributes(取de 字段进行验证)和$value(取字段的值),并返回true 或false。方法message在失败时检索消息。

    在我提到的客户示例中,请按照以下步骤操作:

    1. php artisan make:rule ValidateFieldsClients

    2. 在 composer 创建 ValidateFieldsClients 的类中,我必须声明一个方法来验证传递中的字段,我使用此方法来验证两个字段(code_clientemail) .

    3. 接下来我完成de方法消息以在视图中向用户检索问题

    4. 另外我声明了一个属性 $field 来识别它有错误的字段是什么

    5. ValidateFieldsClients 类示例:

           /***/class ValidateFieldsClients implements Rule{protected $field; /**
           * Create a new rule instance.
           *
           * @return void
           */
          public function __construct()
          {                
          }
      
          /**
           * Determine if the validation rule passes.
           *
           * @param  string  $attribute
           * @param  mixed  $value
           * @return bool
           */
          public function passes($attribute, $value)
          {
              $clients = client::all();   
              $this->field = $attribute;
      
              foreach ($clients as $client ) {
                  if ($value == Crypt::decryptString($client->$attribute)) return false;            
              } 
      
              return true;
          }
      
          /**
           * Get the validation error message.
           *
           * @return string
           */
          public function message()
          {
              return strtoupper($this->field).' exists, check.';
          }
      }
      
    6. 然后验证我使用表单请求验证 (https://laravel.com/docs/8.x/validation#form-request-validation)

    7. php artisan make:request ClientRequest

    8. 并且在最近创建的类的 validate 方法中:

      class ClientRequest extends FormRequest
      {   /**
           * Determine if the user is authorized to make this request.
           *
           * @return bool
           */
          public function authorize()
          {
              return true;  } 
      
      
      /**
       * Get the validation rules that apply to the request.
       *
       * @return array
       */
      public function rules()
      {
      
          return [ 
              'code_client'=> ['required', new ValidateFieldsClients],                
              'email'=>['required', new ValidateFieldsClients],
          ];
      }
      
    9. 终于在控制器中:

       public function store(ClientRequest $request)
              { $clientRequest = $request->validated();
                  foreach ($clientRequest as $key => $client) {
                      $encryptedClient[$key] = Crypt::encryptString($client);
                  };      client::create($encryptedClient+ [
                  'idorga' => 1,
                  'idcrea' => 1,
                  'idmodifica' => 1
              ]);
      
              return redirect('clientes/create')->with('success', 'Registro creado correctamente');
              //return redirect('cuadros')->with('success', 'Registro exitoso!');
          }
      

    【讨论】:

    • 如果您有成千上万的客户,执行验证需要很长时间
    猜你喜欢
    • 2014-04-22
    • 2017-04-11
    • 2018-02-18
    • 2019-02-12
    • 2016-11-22
    • 2015-01-26
    • 2016-01-13
    • 2017-07-25
    • 2018-05-25
    相关资源
    最近更新 更多