我有一个WYSIWYG编辑器.当用户在编辑器中持续按空格时,输入将如下所示.
"<p> </p>"
为了防止这种情况,我修改了Request类中的all方法,以删除空格和标记.
public function all()
{
$input = parent::all();
$input['body'] = strip_tags(preg_replace('/\s+/', '', str_replace(' ',"", $input['body'])));
//modify input here
return $input;
}
这非常有效.
但是,这里的问题是如果其他验证规则失败,则由该方法修改旧辅助函数的返回值.
所以,如果原始输入是这样的
"""
<p> <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(' ',"", $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までアップロードできます',
];
}
}
解决方法:
创建一个自定义验证器,用于剥离标记,计算字符但不修改内容本身.
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(' ',"", $value)
)
)
) >= $parameters[0];
});
'strip_min' => 'The :attribute must be at least :strip_min characters.'
source: https://stackoverflow.com/a/33414725/2119863
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。