如何在控制器Laravel中编写自定义验证规则?

时间:2016-12-22 12:56:59

标签: laravel laravel-5.3

我在控制器Laravel中有默认验证规则:

$validator = Validator::make($request->all(), [
            'email' => 'required|email',
            'phone' => 'required|numeric',
            'code' => 'required|string|min:3|max:4',
            'timezone' => 'required|numeric',
            'country' => 'required|integer',
            'agreement' => 'accepted'
        ]);

我尝试了这个,但不知道如何在函数内传递一些参数:

 public function boot()
    {
        Validator::extend('phone_unique', function($attribute, $value, $parameters) {
            return substr($value, 0, 3) == '+44';
        });
    }

如何根据自己的规则扩展此验证?例如,我需要验证输入的连接:

$phone = $request->code.' '.$request->phone

检查数据库中是否存在$phone

我想使用这种方法:

>  $validator->sometimes('phone', 'required|alpha_dash|max:25', function
> ($input) {
>             if ((Auth::user()->phone == $input->phone)) {
>                 return false;
> 
>             } else {
> 
>                 $t = User::where("phone", $input->phone)->get();
>                 return ($t->count() > 0) ? false : false;
> 
>             }
>         });

它在(True, False)里面的所有条件下都不起作用。

我添加了新的验证nickname_unique

 $validator = Validator::make($request->all(), [
            'email' => 'required|email',
            'code' => 'required|string|min:3|max:4',
            'phone' => 'required|phone_unique',
            'timezone' => 'required|numeric',
            'country' => 'required|integer',
            'nickname' => 'required|alpha_dash|max:25',
            'agreement' => 'accepted'
        ], [
            'phone_unique' => 'Phone already exists!',
            'nickname_unique' => 'Nickname is busy!',
        ]);

它不起作用,甚至不在以下呼叫验证规则:

Validator::extend('nickname_unique', function ($attribute, $value, $parameters, $validator) {

            dd("Here");

});

3 个答案:

答案 0 :(得分:6)

您可以在AppServiceProvider内定义自定义验证器,如下所示:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Validator;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Validator::extend('phone_unique', function ($attribute, $value, $parameters, $validator) {
          $inputs = $validator->getData();
          $code = $inputs['code'];
          $phone = $inputs['phone'];
          $concatenated_number = $code . ' ' . $phone;
          $except_id = (!empty($parameters)) ? head($parameters) : null;

          $query = User::where('phone', $concatenated_number);
          if(!empty($except_id)) {
            $query->where('id', '<>', $except);
          }

          return $query->exists();
      });

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}
  

通过访问$validator属性 - getData()

,您可以获得传递给验证者的所有输入

您可以在自定义验证规则之后(仅在colon之后)向规则数组中添加一个额外参数,如下所示:

'phone' => 'required|phone_unique:1',
  

在将条目检入db

时,传递要忽略的id

自定义验证器Closure接收四个参数:正在验证的$attribute的名称,属性的$value,传递给规则的$parameters数组以及Validator实例

现在您可以像这样调用验证器:

$validator = Validator::make($request->all(), [
      'email' => 'required|email',
      'code' => 'required|string|min:3|max:4',
      'phone' => 'required|phone_unique:1',
      'timezone' => 'required|numeric',
      'country' => 'required|integer',
      'agreement' => 'accepted'
  ], [
    'phone_unique' => 'Phone already exists!', // <---- pass a message for your custom validator
  ]);

详细了解Custom Validation Rules

答案 1 :(得分:3)

我正在写这个答案,因为我相信很多人都在为这个话题寻找一些好的答案。所以我决定分享我用于预订网站的代码,我想在那里检查IS NOT_adate&gt; DEPARTURE_DATE。

我的Laravel版本是5.3.30

public function postSolitudeStepTwo(Request $request)
{
    $rules = [
        'arrival_date' => 'required|date',
        'departure_date' => 'required|departure_date_check',
        'occasional_accompaniment_requested' => 'required|integer',
        'accommodation' => 'required|integer',
        'are_you_visiting_director' => 'required|integer',
    ];

    if ($request->input('are_you_visiting_director') == 1) {
        $rules['time_in_lieu'] = 'required|integer';
    }

    $messages = [
        'departure_date_check' => 'Departure date can\'t be smaller then Arrival date.Please check your dates.'
    ];

    $validation = validator(
        $request->toArray(),
        $rules,
        $messages
    );

    //If validation fail send back the Input with errors
    if($validation->fails()) {
        //withInput keep the users info
        return redirect()->back()->withInput()->withErrors($validation->messages());
    } else {
        MySession::setSessionData('arrival_date', $request);
        MySession::setSessionData('departure_date', $request);
        MySession::setSessionData('occasional_accompaniment_requested', $request);
        MySession::setSessionData('accommodation', $request);
        MySession::setSessionData('are_you_visiting_director', $request);
        MySession::setSessionData('time_in_lieu', $request);
        MySession::setSessionData('comment_solitude_step2_1', $request);

        //return $request->session()->all();
        return redirect("/getSolitudeStepThree");
    }
}

我的控制器是 StepController ,我已经声明了一个名为postSolitudeStepTwo的方法。我宣布规则并在出发日期通知我们有required|departure_date_check规则。这将是

中方法的名称
app/Providers/AppServiceProvider.php

那里的代码如下:

public function boot()
{
    Validator::extend('departure_date_check', function ($attribute, $value, $parameters, $validator) {
        $inputs = $validator->getData();
        $arrivalDate = $inputs['arrival_date'];
        $departureDate = $inputs['departure_date'];
        $result = true;
        if ($arrivalDate > $departureDate) {
            $result = false;
        }
        return $result;
    });
}

由于Laravel documentation 5.3 Custom validation rules我们需要扩展Validator外观,所以该方法的签名必须是:

Validator::extend(name_of_the_function, function ($attribute, $value, $parameters, $validator) {

我相信其余的都很明确。

希望它会对某人有所帮助。

Cutom Validation error frontend

答案 2 :(得分:1)

$messsages = array(
        'email.required'=>'Email is Required',
        'phone.required'=>'Phone number is Required',

    );

    $rules = array(
        'email' => 'required',
        'phone' => 'required',

    );

    $validator = Validator::make(Input::all(), $rules,$messsages);



    if ($validator->fails()):
        $this->throwValidationException($request, $validator);
    endif;