2016-07-17 5 views
3

내가 Laravel 5.2을 사용하고 있습니다를 사용하고, 문서로 말한다 없습니다부울 검증 laravel 5

부울

검증 아래의 필드가 부울로 캐스팅 할 수 있어야합니다. 허용되는 입력은 true, false, 1, 0, "1"및 "0"입니다.

따라서 checkbox (styled like a switch from materialize)을 만들었습니다. 켜져 있으면 true를 표시하고 꺼져 있으면 false를 반환합니다. 블레이드는 다음과 같습니다.

{!! Form::hidden('eh_capa', 0) !!} 
Want to select as a graph cover? 
<label> 
    Off 
    <input name="cover" type="checkbox" checked> 
    <span class="lever"></span> 
    on 
</label> 

물론이 코드는 양식 태그 안에 있습니다.

public function rules() 
{ 
    $this['cover'] = $this['cover'] === 'on' ? 1 : 0; 
    $this['obra_id'] = $this->route('obra'); 
    $this['arquivo'] = $this->hasFile('arquivo') ? $this->file('arquivo') : NULL; 
    dd($this); 
    return [ 
     'cover' => 'required|boolean', 
     'obra_id' => 'exists:obras', 
     'path' => 'required', 
     'arquivo' => 'required|file|max:2048|mimes:pdf', 
    ]; 
} 

DD 형식() 함수 내이 같은 요청을 반환합니다 :

StoreGraficoPostRequest {#441 ▼ 
    #container: Application {#3 ▶} 
    #redirector: Redirector {#448 ▶} 
    #redirect: null 
    #redirectRoute: null 
    #redirectAction: null 
    #errorBag: "default" 
    #dontFlash: array:2 [▶] 
    #json: null 
    #convertedFiles: array:1 [▶] 
    #userResolver: Closure {#355 ▶} 
    #routeResolver: Closure {#354 ▶} 
    +attributes: ParameterBag {#443 ▶} 
    +request: ParameterBag {#440 ▼ 
    #parameters: array:5 [▼ 
     "_token" => "bZIpGW6UCcYHlCTZuIZMtmOrpCodWyfcbO1HgQid" 
     "path" => "hello.pdf" 
     "cover" => 1 
     "obra_id" => "29" 
     "arquivo" => UploadedFile {#438 ▶} 
    ] 
    } 
    +query: ParameterBag {#442 ▶} 
    +server: ServerBag {#446 ▶} 
    +files: FileBag {#445 ▶} 
    +cookies: ParameterBag {#444 ▶} 
    +headers: HeaderBag {#447 ▶} 
    #content: "" 
    #languages: null 
    #charsets: null 
    #encodings: null 
    #acceptableContentTypes: null 
    #pathInfo: null 
    #requestUri: null 
    #baseUrl: null 
    #basePath: null 
    #method: "POST" 
    #format: null 
    #session: Store {#394 ▶} 
    #locale: null 
    #defaultLocale: "en" 
} 

그러나 때를 laravel 문서의 this part에 말했듯이 요청 클래스 내부의 유효성 검사를 수행 여기 내 규칙 방법 dd 함수에 주석을 달아라. 검증은 true 또는 false 여야한다는 것을 반환한다. 표지 필드의 값을 true로 변경하면 "1"과 "true"가 켜져도 마찬가지입니다. 나는 모든 웹에서 도움이되고 아무것도 얻지 못했습니다 ... 나는 이것이 Laravel 버그라고 생각하기 시작했습니다. ...

+0

그것은 laravel 버그 아니다. 현재 프로젝트에서 laravel 5.2를 사용하여 부울 검증을 사용합니다. 유효성 검사 규칙 내에서 요청 값을 설정하는 이유가 있습니까? –

+0

아니, 이유가 없었어 ... 나는 그들이 나의 요청에 나타나도록 강요하려고 노력했다. 그러나 나는 @ sameeranand1이 이것을하는 방법에 대한 내 견해를 바꾸 었다고 생각한다. –

+0

@ThalesNathan'''$ this -> [ 'field']'''는 실제로 일종의 뮤 테이터를 얻습니다.이 값은 이렇게 바꿀 수 없습니다;) –

답변

0

입력을 다른 곳에서 수정하고 있습니다. 요청 클래스의 all() 함수를 재정의하고 입력 클래스를 수정해야합니다.

public function rules() 
{ 
    return [ 
     'cover' => 'required|boolean', 
     'obra_id' => 'exists:obras', 
     'path' => 'required', 
     'arquivo' => 'required|file|max:2048|mimes:pdf', 
    ]; 
} 

public function all() 
{ 
    $input = parent::all(); 

    $input['cover'] = $input['cover'] === 'on' ? 1 : 0; 
    $input['obra_id'] = ... 
    $input['arquivo'] = ... 

    return $input; 
} 
+0

This ** parent : all() ** seem 일하지 않으려면 ... 대신 $ this-> all() _라고 생각하지 않습니까? –

+0

좋아, 알았어, _parent 대신 _parent :: all() _을 사용했다 : all() _ 이제 내 요청이 거부되었다 (ERR_CONNECTION_RESET을 리턴한다). _all_ 메소드 오버라이드를 주석 처리하면 이전에 게시 한 것과 동일한 문제가 발생합니다. –

+0

미안하지만 그건 내 실수 였어. 예, _parent :: all() _입니다. 이로 인해 ERR_CONNECTION_RESET이 발생하지 않아야합니다.나는 그것이 어디에서 오는 것인지 너무 확신하지 못한다. –

1

글쎄, 나는 그것을 할 방법이있다. 트릭은이 코드를 내 Request 클래스에 추가하는 것일뿐입니다.

protected function getValidatorInstance() 
{ 
    $data = $this->all(); 
    $data['eh_capa'] = $data['eh_capa'] === 'on' ? 1 : 0; 
    $data['obra_id'] = $this->route('obra'); 
    $this->getInputSource()->replace($data); 

    /* modify data before send to validator */ 

    return parent::getValidatorInstance(); 
} 

그런 다음 내 규칙 메소드가 리턴으로 만 종료되었습니다.

0

동일한 문제가 발생하여 규칙에서 부울로 표시된 모든 값을 구문 분석하는 작은 정적 클래스를 만들기로 결정했습니다.

장점은 규칙이 부울로 규정하는 불리언 만 구문 분석한다는 것입니다. 다른 입력 값은 변경되지 않으므로 필요에 따라 'true'값을 갖는 문자열을 게시 할 수 있습니다.

<?php 

namespace App\Helpers; 

use Illuminate\Http\Request; 
use Illuminate\Support\Facades\Validator; 

class ValidationHelper { 

    /** 
    * A recursive funciton to loop over any input and parse them to true booleans. 
    */ 
    private static function _getObj(&$inputs, $idPath) { 
     $idPart = array_shift($idPath); 

     if (count($idPath) > 0) { 
      if ($idPart == '*') { 
       for ($i = 0; $i < count($inputs); $i++) { 
        ValidationHelper::_getObj($inputs[$i], $idPath); 
       } 
      } 
      else { 
       ValidationHelper::_getObj($inputs[$idPart], $idPath); 
      } 
     } 
     else { 
      $currentValue = $inputs[$idPart]; 
      if ($currentValue == 1 || strtolower($currentValue) == 'true') { 
       $inputs[$idPart] = true; 
      } 
      else if ($currentValue == 0 || strtolower($currentValue) == 'false') { 
       $inputs[$idPart] = false; 
      } 
      else { // any other value will be left untouched 
       $inputs[$idPart] = $currentValue; 
      } 
     } 
    } 

    /** 
    * Will validate a request against the given rules. 
    * Will also help fix any booleans that otherwise are parsed as 'true' strings. 
    * @param Request $request 
    * @param Array $rules  
    * @return void 
    */ 
    public static function validateRequest(Request $request, $rules) { 
     // Find any rules demanding booleans: 
     $booleanIDs = []; 
     foreach ($rules as $id => $rule) { 
      if (is_string($rule)) { 
       $rule = explode('|', $rule); 
      } 
      if (in_array('boolean', $rule)) { 
       $booleanIDs[] = $id; 
      } 
     } 

     if (isset($booleanIDs)) { 
      // Set all inputs to a bindable array: 
      $inputs = []; 
      foreach ($request->all() as $key => $value) { 
       $inputs[$key] = $value; 
      } 

      // Recursively loop through the boolean-ids 
      foreach ($booleanIDs as $id) { 
       $idPath = explode('.', $id); 
       ValidationHelper::_getObj($inputs, $idPath); 
      } 

      // Make sure the booleans are not just validated correctly but also stay cast when accessing them through the $request later on. 
      $request->replace($inputs); 
     } 
     else { 
      $inputs = $request->all(); 
     } 

     $validator = Validator::make($inputs, $rules); 
     if ($validator->fails()) { 
      throw new \Exception('INVALID_ARGUMENTS', $validator->errors()->all()); 
     } 
    } 

} 

규칙은 어레이 또는 문자열로 설정 (통상 등)과도 중첩 값으로 작동 될 수

ValidationHelper::validateRequest($request, [ 
      ['foo'] => ['nullable', 'boolean'], 
      ['bar'] => ['required', 'boolean'], 
      ['item.*.isFoo'] => ['nullable', 'boolean'], 
      ['item.*.isBar'] => 'required|boolean'], 
     ]);