【问题标题】:how do i write the validation in the model in laravel?我如何在 laravel 的模型中编写验证?
【发布时间】:2020-06-16 05:09:17
【问题描述】:

当我在控制器中验证 电话号码 时,它正在工作,但它增加了代码行数,我还必须编写回调函数,但我不想编写回调,而不是我想在模型中做,有什么办法吗??

'phone' =>['required',"regex:/^\(?[\d]{3}\)?[\s-]?[\d]{3}[\s-]?[\d]{4}$/",function($attribute, $value, $fail) use($id) {

                    if (strpos($value, "-") !== false) {
                        $exist = User::where([["phone", $value],["id","!=",$id]])->count();
                        if($exist){
                            $fail(ucwords($attribute).' is already taken.');
                        }else{
                            $result = User::where([["phone", str_replace("-","",$value)],["id","!=",$id]])->count();
                            ($result) ?  $fail(ucwords($attribute).' is already taken.') : "";
                        }

                    }else{
                        $exist = User::where([["phone", $value],["id","!=",$id]])->count();
                        if($exist){
                            $fail(ucwords($attribute).' is already taken.');
                        }
                    }
                },],

【问题讨论】:

    标签: php laravel php-7.2 laravel-6.2


    【解决方案1】:

    我认为您应该能够将模型中的函数定义为返回闭包的静态函数,这样您就可以调用它来获取闭包并将其作为回调传递。

    // In the model
    public static function myValidationClosure($id){
       return function($attribute, $value, $fail)use($id) {
         if (strpos($value, "-") !== false) {
             $exist = User::where([["phone", $value],["id","!=",$id]])->count();
             if($exist){
                 $fail(ucwords($attribute).' is already taken.');
             }else{
                 $result = User::where([["phone", str_replace("-","",$value)],["id","!=",$id]])->count();
                 ($result) ?  $fail(ucwords($attribute).' is already taken.') : "";
             }
         }else{
             $exist = User::where([["phone", $value],["id","!=",$id]])->count();
             if($exist){
                 $fail(ucwords($attribute).' is already taken.');
             }
         }
       };
     }
    

    然后你可以在验证中使用它作为

    'phone' =>['required',"regex:/^\(?[\d]{3}\)?[\s-]?[\d]{3}[\s-]?[\d]{4}$/", MyModelClass::myValidationClosure($id)]
    

    【讨论】:

      【解决方案2】:

      对于验证而言,好的解决方案总是提出一个单独且易于处理的自定义请求,请遵循此 =>

      php artisan make:request CustomRequest

      请求:

      <?php
      
      namespace App\Http\Requests;
      
      use Illuminate\Foundation\Http\FormRequest;
      use App\User;
      
      class CustomRequest 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 [
      
                  'phone'        => [
                                          'required',
      
                                          'min:10', 
                                          'max':10',             
                                          'regex:/^\(?[\d]{3}\)?[\s-]?[\d]{3}[\s-]?[\d]{4}$/',     
      
                                       ],
      
              ];
          }
      }
      

      它将为您提供默认验证消息,但如果您想制作自定义消息,您可以通过 message() 来完成

      https://laravel.com/docs/7.x/validation

      希望对你有帮助!

      【讨论】:

      • 谢谢,我明白了,但是有没有办法不写我正在使用的回调,因为正如你所建议的那样它只会验证正则表达式,但它不会验证数字是否存在于数据库中或不像回调。再次感谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-27
      • 1970-01-01
      • 2017-10-04
      • 2019-12-24
      • 2016-09-11
      相关资源
      最近更新 更多