Laravel 如何在第一次错误后停止验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46013320/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:35:32  来源:igfitidea点击:

Laravel how to stop validation after first error

phplaravelvalidation

提问by Wini the Pooh

I don't have a clue how to make laravel validatestop validation after first error occurs and then return only one error

我不知道如何在第一个错误发生后使laravel 验证停止验证,然后只返回一个错误

Rules with val_ prefix are my custom rules.

带有 val_ 前缀的规则是我的自定义规则。

I need to display only error for peselfield if the peselfield is empty('required' rule) Could anyone tell me how can I reach that ?

如果pesel字段为空,我只需要显示pesel字段的错误('required' 规则) 谁能告诉我我怎样才能达到那个?

$this->validate($request, [

    'pesel'=> 'bail|required|val_pesel',
    'dane_os' => 'required',
    'id_project' => 'required',
    'imie' => 'required|val_imie',
    'nazwisko'=>'required|val_nazwisko',
    'nazwisko_matki'=>'required|val_nazwisko_matki'

]);

MY VALIDATION CODE

我的验证码

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

      $val = DB::select('select * from  `wyborca` where pesel = "'.$value.'"  ; ');
      if(empty($val))
      {
        return false;
      }
      else {
        return true;
      }
    });
    Validator::extend('val_imie',function($attribute,$value,$parameters,$validator)
    {
       $test = $validator->getData();
       $pesel = $test['pesel'];
       $imie = $test['imie'];




      $val = DB::select('select * from  `wyborca` where pesel = "'.$pesel.'" and imie = "'.$imie.'" ; ');
      if(empty($val))
      {
        return false;
      }
      else {
        return true;
      }
    });
    Validator::extend('val_nazwisko',function($attribute,$value,$parameters,$validator)
    {
       $test = $validator->getData();
       $pesel = $test['pesel'];
       $nazwisko = $test['nazwisko'];




      $val = DB::select('select * from  `wyborca` where pesel = "'.$pesel.'" and nazwisko = "'.$nazwisko.'" ; ');
      if(empty($val))
      {
        return false;
      }
      else {
        return true;
      }
    });
    Validator::extend('val_nazwisko_matki',function($attribute,$value,$parameters,$validator)
    {
       $test = $validator->getData();
       $pesel = $test['pesel'];
       $nazwisko_matki = $test['nazwisko_matki'];




      $val = DB::select('select * from  `wyborca` where pesel = "'.$pesel.'" and nazwisko_matki = "'.$nazwisko_matki.'" ; ');
      if(empty($val))
      {
        return false;
      }
      else {
        return true;
      }
    });
    Validator::extend('vote_exists',function($attribute,$value,$parameters,$validator)
    {
       $test = $validator->getData();
       $pesel = $test['pesel'];




      $val = DB::select('select * from  `glosy` where pesel = "'.$pesel.'"  ; ');
      if(empty($val))
      {
        return false;
      }
      else {
        return true;
      }
    });

}

回答by dav

To stop validation if the first rule fails you should use bail, quote from docs

要在第一条规则失败时停止验证,您应该使用bail,引用文档

Stopping On First Validation Failure Sometimes you may wish to stop running validation rules on an attribute after the first validation failure. To do so, assign the bail rule to the attribute:

在第一次验证失败时停止 有时您可能希望在第一次验证失败后停止对属性运行验证规则。为此,请将保释规则分配给属性:

$this->validate($request, [
    'title' => 'bail|required|unique:posts|max:255',
    'body' => 'required',
]);

In this example, if the required rule on the title attribute fails, the unique rule will not be checked. Rules will be validated in the order they are assigned.

在本例中,如果title 属性上的required 规则失败,则不会检查唯一规则。规则将按照分配的顺序进行验证。

https://laravel.com/docs/5.5/validation

https://laravel.com/docs/5.5/validation

here is the github discussion https://github.com/laravel/framework/issues/4789#issuecomment-174837968

这是 github 讨论 https://github.com/laravel/framework/issues/4789#issuecomment-174837968

回答by Bruce Tong

To redirect and stop validation after the first rule has failed you can use the 'bail' keyword. an example:

要在第一条规则失败后重定向和停止验证,您可以使用“保释”关键字。一个例子:

    // $arr = ['form input var'=>'exact word to be used in error msg'] ***

    $arr = ['coverletter'=>'Cover Letter','vitae'=>'CV','certificate'=>'Certificate','tesol'=>'Tesol','photo'=>'Photo'];

    // $this->validate($data,$rules,$messages);
    // we have 2 rules to validate, 'required' & 'mimetypes' so output messages for them must be in an array

    foreach ($arr as $k=>$v) {
        if($k !== 'photo') {

    // Tesol, CV, Certificate must be in PDF format so we can loop through all 3 of them here

        if(!Session::get($k) || $request->$k) {     

    // user has submitted before but is submitting again, we evaluate the request
    // user has not submitted before, we evaluate the request   

            $this->validate($request,
                [$k => 'bail|required|mimetypes:application/pdf'],
                [$k . '.required' => $v . ' is required',
                $k . '.mimetypes' => $v . ' must be PDF']);
            }
        }
        if($k == 'photo') {

            if(!Session::get($k) || $request->$k) {         

            $this->validate($request,
                [$k => 'bail|required|mimetypes:image/jpg,image/jpeg'],
                [$k . '.required' => $v . ' is required',
                $k . '.mimetypes' => $v . ' must be of type jpeg']);
            }
        }
    }

this will redirect back with your error message after the first rule failed.

这将在第一条规则失败后重定向回您的错误消息。