我有一个所见即所得的编辑器。当用户在编辑器中一直按空格时,输入将是这样的。
"<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;
}
这很好用。
但是,这里的问题是如果其他验证规则失败,old 辅助函数的返回值将被该方法修改。
那么,如果原来的输入是这样的
"""
<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];
});
并在您的 validation.php 语言文件中添加:
'strip_min' => 'The :attribute must be at least :strip_min characters.'
关于php - Laravel 验证在验证之前修改请求。失败返回原件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42344997/
给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru
我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..
为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返
我希望我的UserPrice模型的属性在它们为空或不验证数值时默认为0。这些属性是tax_rate、shipping_cost和price。classCreateUserPrices8,:scale=>2t.decimal:tax_rate,:precision=>8,:scale=>2t.decimal:shipping_cost,:precision=>8,:scale=>2endendend起初,我将所有3列的:default=>0放在表格中,但我不想要这样,因为它已经填充了字段,我想使用占位符。这是我的UserPrice模型:classUserPrice回答before_val
我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss
在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这
我有一些非常大的模型,我必须将它们迁移到最新版本的Rails。这些模型有相当多的验证(User有大约50个验证)。是否可以将所有这些验证移动到另一个文件中?说app/models/validations/user_validations.rb。如果可以,有人可以提供示例吗? 最佳答案 您可以为此使用关注点:#app/models/validations/user_validations.rbrequire'active_support/concern'moduleUserValidationsextendActiveSupport:
当我的预订模型通过rake任务在状态机上转换时,我试图找出如何跳过对ActiveRecord对象的特定实例的验证。我想在reservation.close时跳过所有验证!叫做。希望调用reservation.close!(:validate=>false)之类的东西。仅供引用,我们正在使用https://github.com/pluginaweek/state_machine用于状态机。这是我的预订模型的示例。classReservation["requested","negotiating","approved"])}state_machine:initial=>'requested
我有一个服务模型/表及其注册表。在表单中,我几乎拥有服务的所有字段,但我想在验证服务对象之前自动设置其中一些值。示例:--服务Controller#创建Action:defcreate@service=Service.new@service_form=ServiceFormObject.new(@service)@service_form.validate(params[:service_form_object])and@service_form.saverespond_with(@service_form,location:admin_services_path)end在验证@ser
我有一个包含多个键的散列和一个字符串,该字符串不包含散列中的任何键或包含一个键。h={"k1"=>"v1","k2"=>"v2","k3"=>"v3"}s="thisisanexamplestringthatmightoccurwithakeysomewhereinthestringk1(withspecialcharacterslike(^&*$#@!^&&*))"检查s是否包含h中的任何键的最佳方法是什么,如果包含,则返回它包含的键的值?例如,对于上面的h和s的例子,输出应该是v1。编辑:只有字符串是用户定义的。哈希将始终相同。 最佳答案