2017-02-20 71 views
4

我有一個所見即所得的編輯器。當用戶在編輯器中保持按壓空間時,輸入將如此。驗證前Laravel驗證修改請求。如果失敗返回原始

"<p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</p>" 

爲了防止這一點,我修改了all方法Request類這樣的去除空白和標籤。

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

    $input['body'] = strip_tags(preg_replace('/\s+/', '', str_replace('&nbsp;',"", $input['body']))); 
    //modify input here 

    return $input; 
} 

這很好。

但是,這裏的問題是,如果其他驗證規則失敗,則該方法會修改幫助函數返回值old

所以,如果原來的輸入是這樣

""" 
<p>&nbsp;<iframe src="//www.youtube.com/embed/Mb5xcH9PcI0" width="560" height="314" allowfullscreen="allowfullscreen"></iframe></p>\r\n 
<p>This is the body.</p> 
""" 

如果其他驗證規則失敗,我得到這個作爲一個老的輸入。

"Thisisthebody."

那麼,有沒有什麼辦法讓原始請求輸入作爲一個老輸入驗證時失敗了嗎?

這是我的表單請求。

<?php 

namespace App\Http\Requests; 

use App\Http\Requests\Request; 
use Illuminate\Validation\Factory as ValidationFactory; 

class ArticleRequest extends Request 
{ 

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

    $input['body'] = strip_tags(preg_replace('/\s+/', '', str_replace('&nbsp;',"", $input['body']))); 
    //modify input here 

    return $input; 
} 

/** 
* 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 [ 
     'title' => 'required|min:3|max:40', 
     'tags.*' => 'required', 
     'body' => 'required|min:50', 
     //up to 6mb 
     'thumbnail'=>'image|file|max:10240' 
    ]; 
} 

public function messages() 
{ 
    return [ 
     'title.required' => 'タイトルを入力してください', 
     'title.min' => 'タイトルは3文字以上でお願いします', 
     'title.max' => 'タイトルは40文字以下でお願いします', 
     'body.min' => '本文は50文字以上お書きください', 
     'body.required' => '本文を入力してください', 
     'tags.*.required' => 'タグを選んでください', 
     'thumbnail.image' => '畫像の形式はjpeg, bmp, png, svgのいずれかをアップロードできます', 
     'thumbnail.file' => 'フォームから畫像をもう一度アップロードしてください', 
     'thumbnail.max' => 'ファイルは10MBまでアップロードできます', 
    ]; 
} 
} 
+1

也許你可以備份修改之前的原始值? '$ input ['original_body'] = $ input ['body'];'然後嘗試在您的視圖中回退到'original_body'?我知道我的想法有味道,我只是想在這裏點燃一些想法。 –

+0

使用'session()'來做到這一點?這可能是一個選擇。讓我看看有人有其他解決方案。謝謝你的評論。 – shigg

+1

如果有什麼智慧出現,我會ping我。 –

回答

0

創建一個自定義驗證程序,它剝離標記,計數字符但不會修改內容本身。

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

    $validator->addReplacer('strip_min', function($message, $attribute, $rule, $parameters){ 
     return str_replace([':min'], $parameters, $message); 
    }); 

    return strlen(
     strip_tags(
      preg_replace(
       '/\s+/', 
       '', 
       str_replace('&nbsp;',"", $value) 
      ) 
     ) 
    ) >= $parameters[0]; 
}); 

,並在您validation.php郎文件中加入:

'strip_min' => 'The :attribute must be at least :strip_min characters.' 

source: https://stackoverflow.com/a/33414725/2119863