草庐IT

php - Laravel 5.2 验证错误在随机时刻为空

coder 2024-04-22 原文

我的 Laravel 应用程序验证发生了一些非常奇怪的事情。我有一个应用程序,用户只能在 url 中使用他/她的唯一哈希/代码访问它。当带有散列的 url 与用户匹配时,我会使用用户的个人资料信息预先填写表格。然后用户必须在使用表格时确认/完成/修改信息。这工作正常,但在提交表单时有时验证行为不正常。

例如,我将一些必填字段留空并提交表单,我被重定向回来,我的错误显示在带有漂亮红色边框的表单字段中。到目前为止一切都很好。但是,由于某些未知原因,有时在验证所需的字段中提交带有空值的表单时,它会重定向回来并再次显示预填写的配置文件表单,但错误变量为空,但验证仍然失败!

发生这种情况时,他们无法划清界线,有时它会在第一次提交时发生,有时我必须提交表单 30 次才能发生。现在我们通过额外的前端验证层来解决它,因为应用程序必须上线,但我无法停止思考为什么会发生这种情况以及如何发生。

我正在使用 Request 类进行验证,但我也尝试在我的 Controller 中创建一个手动验证器,但它具有完全相同的行为。我一开始以为是预填表单的问题,所以我尝试了当有错误的时候我不预填任何东西(当然除了input old),但问题仍然存在。

最奇怪的部分是错误是空的,但是一些必填字段没有填写(而且他们的名字是正确的)因为问题并不总是发生。我一直无法在我的本地和暂存环境中重现该问题,但它一直在我的实时服务器上发生。

如果有人对我做错了什么或发生了什么有任何建议,那就太好了。我这样做了 1000 次,与其他时间的唯一区别是我预先填写了表格,但是当我关闭该功能时我也有它。

编辑: 根据下面我的代码的要求。 注意:我替换了一些关键字,例如路由、重定向和关系名称。

请求类

<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;

class RegistrationRequest extends Request
{
    /**
     * 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 [
            'hash'       => 'required|exists:users,hash',
            'language'   => 'required|in:NLD,FRA',
            'title'      => 'required',
            'firstName'  => 'required',
            'lastName'   => 'required',
            'street'     => 'required',
            'postalCode' => 'required',
            'city'       => 'required',
            'email'      => 'required|email',
            'birthday'   => 'required|date_format:d/m/Y',
            'tac'        => 'required'
        ];
    }
}

Controller 方法索引。

public function index($hash)
{
   $user = $this->user->byHash($hash);

   if(is_null($user)) {
      return redirect()->to('/');
   }

   if(! is_null($user->myRelationName)) {
      return redirect()->route('thanks');
   }

   return view('my-view', ['user' => $user]);
}

Controller 方法库

public function store(RegistrationRequest $request)
{
    $user             = $this->user->byHash($request->hash);
    $user->language   = $request->language;
    $user->title      = $request->title;
    $user->firstName  = $request->firstName;
    $user->lastName   = $request->lastName;
    $user->street     = $request->street;
    $user->postalCode = $request->postalCode;
    $user->city       = $request->city;
    $user->email      = $request->email;
    $user->birthday   = $request->birthday;
    $user->tac        = true;
    $user->ip         = $this->getRemoteIPAddress();
    $user->save();

    return redirect()->route('my-route', ['hash' => $request->hash]);
}

查看.blade.php

@extends('layouts.master')

@section('content')


<div class="bottom">
    <div class="form-container">

        <h2>{{trans('merci.register_maintitle')}}</h2>
        <p>{!!trans('merci.register_p1')!!}</p>

        <p>{!!trans('merci.register_p2')!!}</p>

        <h3>{!!trans('merci.register_h3')!!}</h3>

        {{ Form::open(['route' => 'register.store', 'class' => 'form', 'id' => "register-form"]) }}
            {{Form::hidden('hash', $user->hash, array("id" => "hash"))}}

            <div class="form-field-wrap form-group language {{$errors->has('language')  ? 'has-error' : null}}">
                {{ Form::label('language', trans('merci.register_language'), array('class' => 'form-field-text-label radio-label'))}}

                {{ Form::radio('language', trans('merci.register_language1_value'), ($user->language == trans('merci.register_language1_value')) ? true : false, array('id' => 'nl-rad')) }}
                <span>{{trans('merci.register_language1_label')}}</span>

                {{ Form::radio('language', trans('merci.register_language2_value') , ($user->language == trans('merci.register_language2_value')) ? true : false, array('class' => 'radio', "id"=> 'fr-rad')) }} 
                <span>{{trans('merci.register_language2_label')}}</span>
            </div>

            <div class="form-field-wrap form-group title {{$errors->has('title')  ? 'has-error' : null}}">

                {{ Form::label('title', trans('merci.register_title'), array('class' => 'form-field-text-label radio-label'))}}

                {{ Form::radio('title', trans('merci.register_title1_value'), ($user->title == trans('merci.register_title1_value')) ? true : false) }} 
                <span>{{trans('merci.register_title1_label')}}</span>

                {{ Form::radio('title', trans('merci.register_title2_value'), ($user->title == trans('merci.register_title2_value')) ? true : false, array('class' => 'radio')) }} 
                <span>{{trans('merci.register_title2_label')}}</span>
            </div>

            <div class="form-field-wrap form-group lastName {{$errors->has('lastName')  ? 'has-error' : null}}">
                {{ Form::label('lastName', trans('merci.register_lastName'), array('id' => 'lastName', 'class' => 'form-field-text-label'))}}

                {{ Form::text('lastName', $user->lastName, array('class' => 'form-field-text-input')) }}
            </div>

            <div class="form-field-wrap form-group firstName {{$errors->has('firstName')  ? 'has-error' : null}}">
                {{ Form::label('firstName', trans('merci.register_firstName') , array('class' => 'form-field-text-label'))}}

                {{ Form::text('firstName', $user->firstName, array('class' => 'form-field-text-input')) }}
            </div>

            <div class="extramargin form-field-wrap form-group street {{$errors->has('street')  ? 'has-error' : null}}">
                {{ Form::label('street', trans('merci.register_street'), array('class' => 'form-field-text-label'))}}

                {{ Form::text('street', $user->street, array('class' => 'form-field-text-input big')) }}
            </div>

            <div class="smallerpostal form-field-wrap form-group postalCode {{$errors->has('postalCode')  ? 'has-error' : null}}">
                {{ Form::label('postalCode', trans('merci.register_postalCode'), array('class' => 'form-field-text-label smaller-label'))}}

                {{ Form::text('postalCode', $user->postalCode, array('class' => 'form-field-text-input smaller')) }}
            </div>

            <div class="smallercity form-field-wrap form-group city {{$errors->has('city')  ? 'has-error' : null}}">

                {{ Form::label('city', trans('merci.register_city'), array('class' => 'form-field-text-label smal-label'))}}

                {{ Form::text('city', $user->city, array('class' => 'form-field-text-input smal')) }}
            </div>

            <div class="extramargin form-field-wrap form-group email {{$errors->has('email')  ? 'has-error' : null}}">
                {{ Form::label('email', trans('merci.register_email'), array('class' => 'form-field-text-label'))}}

                {{ Form::email('email', $user->email, array('class' => 'form-field-text-input ')) }}
            </div>

            <div class="form-field-wrap form-group birthday {{$errors->has('birthday')  ? 'has-error' : null }} ">
                {{ Form::label('birthday', trans('merci.register_birthday'), array('class' => 'form-field-text-label', "id" => "birthdate"))}}

                {{ Form::text('birthday', $user->birthday, array('class' => 'form-field-text-input', "id"=>"datepicker")) }}
            </div>

            <div class="check form-field-wrap form-group  tac {{$errors->has('tac')  ? 'has-error' : null }}">
                {{ Form::checkbox('tac', trans('merci.register_tac_value'), false, array('class' => 'form-field-checkbox', "id" => "tac"))}} 
                {{ Form::label('tac', trans('merci.register_tac_label'), array('class' => 'form-field-error-label')) }}
                <span>{!!trans('merci.register_tac_label_link')!!}</span>
            </div>

            @if (count($errors) > 0)
            <div id="error server" style='display:none;'>
            @else
            <div id="error" style='display:none;'>
            @endif
                <p class="error">{{trans('merci.register_error')}}</p>
            </div>


            {!! Form::submit(trans('merci.register_submit'), array('class' => 'btn-main btn')) !!}
        {{ Form::close() }}
        <small>{{trans('merci.register_mandatory')}}</small>

    </div>
</div>
<script src="{{ asset('js/validate.js') }}"></script>
@stop

最佳答案

我不知道你的路由是否在网络中间件内,但如果你丢失了 $errors 包变量,那可能是原因。

Any routes not placed within the web middleware group will not have access to sessions and CSRF protection (See the default routes file).

当 $errors 变量被 web 中间件组绑定(bind)到 View 时,这个变量将始终在您的 View 中可用。 (参见 Displaying The Validation Errors)。

// Make sure any routes that need access to session features are placed within

Route::group(['middleware' => 'web'], function () {

    Route::get('/', 'MyController@index');
});

另外,我会使用 blade 模板中的旧助手来检索来自先前请求的闪烁输入。

{{ old('username') }} 

关于php - Laravel 5.2 验证错误在随机时刻为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35791454/

有关php - Laravel 5.2 验证错误在随机时刻为空的更多相关文章

  1. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  2. ruby - 具有身份验证的私有(private) Ruby Gem 服务器 - 2

    我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..

  3. ruby-on-rails - Rails 常用字符串(用于通知和错误信息等) - 2

    大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje

  4. ruby-on-rails - 如果为空或不验证数值,则使属性默认为 0 - 2

    我希望我的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

  5. ruby-on-rails - 如何验证非模型(甚至非对象)字段 - 2

    我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss

  6. ruby-on-rails - 如何将验证与模型分开 - 2

    我有一些非常大的模型,我必须将它们迁移到最新版本的Rails。这些模型有相当多的验证(User有大约50个验证)。是否可以将所有这些验证移动到另一个文件中?说app/models/validations/user_validations.rb。如果可以,有人可以提供示例吗? 最佳答案 您可以为此使用关注点:#app/models/validations/user_validations.rbrequire'active_support/concern'moduleUserValidationsextendActiveSupport:

  7. ruby-on-rails - 跳过状态机方法的所有验证 - 2

    当我的预订模型通过rake任务在状态机上转换时,我试图找出如何跳过对ActiveRecord对象的特定实例的验证。我想在reservation.close时跳过所有验证!叫做。希望调用reservation.close!(:validate=>false)之类的东西。仅供引用,我们正在使用https://github.com/pluginaweek/state_machine用于状态机。这是我的预订模型的示例。classReservation["requested","negotiating","approved"])}state_machine:initial=>'requested

  8. ruby-on-rails - 迷你测试错误 : "NameError: uninitialized constant" - 2

    我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test

  9. ruby - 如何在 Rails 4 中使用表单对象之前的验证回调? - 2

    我有一个服务模型/表及其注册表。在表单中,我几乎拥有服务的所有字段,但我想在验证服务对象之前自动设置其中一些值。示例:--服务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

  10. ruby-on-rails - 如何在 Rails View 上显示错误消息? - 2

    我是rails的新手,想在form字段上应用验证。myviewsnew.html.erb.....模拟.rbclassSimulation{:in=>1..25,:message=>'Therowmustbebetween1and25'}end模拟Controller.rbclassSimulationsController我想检查模型类中row字段的整数范围,如果不在范围内则返回错误信息。我可以检查上面代码的范围,但无法返回错误消息提前致谢 最佳答案 关键是您使用的是模型表单,一种显示ActiveRecord模型实例属性的表单。c

随机推荐