加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

php – Laravel验证在验证之前修改请求.如果失败则返回原件

发布时间:2020-12-14 19:37:43 所属栏目:大数据 来源:网络整理
导读:我有一个WYSIWYG编辑器.当用户在编辑器中持续按空格时,输入将如下所示. "pnbsp; nbsp; nbsp; nbsp; nbsp; nbsp; nbsp; nbsp; nbsp; nbsp; nbsp; nbsp; nbsp;/p" 为了防止这种情况,我修改了Request类中的all方法,以删除空格和标记. public function all(){ $i
我有一个WYSIWYG编辑器.当用户在编辑器中持续按空格时,输入将如下所示.

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

为了防止这种情况,我修改了Request类中的all方法,以删除空格和标记.

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

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

    return $input;
}

这非常有效.

但是,这里的问题是如果其他验证规则失败,则由该方法修改旧辅助函数的返回值.

所以,如果原始输入是这样的

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

如果其他验证规则失败,我会将此作为旧输入.

“Thisisthebody.”

那么,当验证失败时,有没有办法将原始请求输入作为旧输入?

这是我的表单请求.

<?php

namespace AppHttpRequests;

use AppHttpRequestsRequest;
use IlluminateValidationFactory as ValidationFactory;

class ArticleRequest extends Request
{

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

    $input['body'] = strip_tags(preg_replace('/s+/',$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'],$message);
    });

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

并在您的validation.php lang文件中添加:

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读