如何在自定义验证规则中使用Laravel的验证规则?

6
我已经输入了$data =['identifier' = 'xxxxxxxxxx'];,并且想要将encrypt($data['identifier'])保存到表格info的主键id列中。
在保存之前,我需要进行验证。规则unique:info, id不适用于此处,因此我想编写自定义验证规则。在自定义验证规则中,我先encrypt()该值,然后使用unique验证规则。
我知道如何编写自定义验证规则,但是如何在我的自定义验证规则中使用unique验证规则呢?

1
https://laravel.com/docs/5.4/validation#custom-validation-rules 不够用吗? - ceejayoz
id 的初始值是什么?它是 int 类型,那么它会被加密吗?! - SaidbakR
@SaidbakR ID 是字符串类型,我需要将其加密后存储在这里。我在这里使用 extend 可能不太合适,我需要一个验证规则,先对输入值进行加密,然后执行唯一性检查。 - LF00
2
@KrisRoofe 你说要“扩展唯一规则”,我觉得这只是个自定义验证规则而已。unique规则只是一个验证规则,你可以根据自己的具体需求创建一个与之类似的规则。 - ceejayoz
@ceejayoz 谢谢。也许我应该把我的问题改成如何在自定义验证规则中使用 Laravel 的验证规则是正确的。 - LF00
显示剩余2条评论
3个回答

3

“unique”和“exists”规则使用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"

1
假设您有一个验证输入的 ModuleRequest,您可以在此类中编写此方法。
protected function validationData() 
{
    $all = parent::validationData();
    $all['email'] = encrypt($all['email']);
    return $all;

}

我知道这个可以用。我想在验证规则中使用encrypt(),就像我在问题中所述的那样。 - LF00

0

Laravel有自定义验证规则(https://laravel.com/docs/8.x/validation#using-rule-objects) 例如,我有一个名为clients的表格,其中有两个唯一字段使用Laravel的加密服务进行加密(https://laravel.com/docs/8.x/encryption),因为它被加密了,所以无法应用验证方法(https://laravel.com/docs/8.x/validation#rule-unique)的唯一指令。这些字段是code_clientemail

这就是实现自定义验证规则的原因。 此服务有两种方法:passesmessage。方法passes接受两个变量:$attributes(要验证的字段)和$value(字段的值),并返回true或false。方法message在失败的情况下检索消息。

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

  1. php artisan make:rule ValidateFieldsClients

  2. 在composer创建的ValidateFieldsClients类中,我必须声明一个方法来验证passes中的字段,我使用此方法来验证两个字段(code_client和email)。

  3. 接下来,我完成了用于在视图中向用户检索问题的消息方法。

  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. 在最近创建的类的验证方法中:

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

如果你有成千上万的客户,执行验证将需要很长时间。 - ManojKiran A

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接