【问题标题】:How to handle this validation context?如何处理这个验证上下文?
【发布时间】:2018-10-08 16:09:57
【问题描述】:

我在下面有这个注册表。

// registration form in the registration page


 <form method="post" id="step1form" action="">
      {{csrf_field()}}
        <p>Is not necessary additional info.
       Your tickets will be sent to the email
     <b>
    {{ (\Auth::check()) ? Auth::user()->email : old('email')}}</b>.</p>

      @if (!empty($allParticipants))
        @if($allParticipants == 1)
            @foreach($selectedTypes as $selectedType)
                @foreach(range(1,$selectedType['quantity']) as $test)
                  <p>Please enter  the following 
                  information for each participant</p>
                  <div class="form-group font-size-sm">
                    <label for="name" class="text-gray">Name</label>
                    <input type="text" required class="form-control" id="name"
                           name="name" value="{{ (\Auth::check()) ? Auth::user()->name : old('name')}}">
                  </div>
                  <div class="form-group font-size-sm">
                    <label for="surname" class="text-gray">Surname</label>
                    <input type="text" id="surname" required class="form-control" name="surname" value="{{ (\Auth::check()) ? Auth::user()->surname : old('surname')}}">
                  </div>

                <h6>Participant - 1 - {{$test}}</h6>

              <div class="form-group font-size-sm">
                <label for="participant_name" class="text-gray">Name</label>
                <input type="text" name="participant_name[]" required class="form-control" value="">
              </div>
              <div class="form-group font-size-sm">
                <label for="participant_surname" class="text-gray">Surname</label>
                <input type="text" required class="form-control" name="participant_surname[]" value="">
              </div>
            <input type="hidden" name="ttypes[]" value="{{ $selectedType['id'] }}"/>
              @foreach($selectedType['questions'] as $customQuestion)
              <div class="form-group">
                <label for="participant_question">{{$customQuestion->question}}</label>
                <input type="text"
                       @if($customQuestion->pivot->required == "1") required @endif
                class="form-control" name="participant_question[]">
                <input type="hidden" name="participant_question_required[]"
                       value="{{ $customQuestion->pivot->required }}">
                <input type="hidden" value="{{ $customQuestion->id }}" name="participant_question_id[]"/>
              </div>
              @endforeach
            @endforeach
        @endforeach
        @endif
      @endif
      <input type="submit" href="#step2" id="goToStep2" value="Go to step 2"/>
    </form> 

如果 congress 表中“all_participants”列为“1”,则用户需要介绍一些注册信息,以介绍每个参与者的信息(姓名和姓氏)。

如果all_participants列为“0”,则显示为“&lt;p&gt;Is not necessary additional info.&lt;/p&gt;”,用户无需介绍任何信息即可注册大会,因为它使用了他的身份验证信息进行大会注册。

但是当 all_participants 列为“0”时,就会出现问题。因为在注册控制器中处理注册的方法中我有一些规则:

 $rules = [
            'name' => 'required|max:255|string',
            'surname' => 'required|max:255|string',
            'email' => 'required|max:255|email',
            'participant_name.*' => 'required|max:255|string',
            'participant_surname.*' => 'required|max:255|string',
        ];

问题: 因此,当 all_participants 列为“0”并且用户单击“转到第 2 步”时,会出现一些验证错误。你知道如何解决这个问题吗?

处理注册的完整方法:

public function storeRegistration(Request $request, $id, $slug = null, Validator $validator){

        $user = Auth::user();

        $rules = [
            'name' => 'required|max:255|string',
            'surname' => 'required|max:255|string',
            'email' => 'required|max:255|email',
            'participant_name.*' => 'required|max:255|string',
            'participant_surname.*' => 'required|max:255|string',
            'participant_email.*' => 'required|max:255|email',
        ];

        $messages = [
            'participant_question.*.required' => 'The participant is required'
        ];

        if($request->participant_question_required){
            foreach ($request->participant_question_required as $key => $value) {
                $rule = 'string|max:255'; 
                // if this was required, ie 1, prepend "required|" to the rule
                if ($value) {
                    $rule = 'required|' . $rule;
                }

                // individual rule for this array key to the $rules array
                $rules["participant_question.{$key}"] = $rule;
            }
        }

        $validator = Validator::make($request->all(), $rules, $messages);

        if($validator->passes())
        {
            $registration = Registration::create([
                'congress_id' => $id,
                'main_user_id' => $user->id,
                'status' => 'C',
            ]);
                if($request->participant_name) {

                    $participants = [];

                    for ($i = 0; $i < count($request->participant_name); $i++)
                        $participants[] = Participant::create([
                            'name' => $request->participant_name[$i],
                            'surname' => $request->participant_surname[$i],
                            'email' => $request->participant_email[$i],
                            'registration_id' => $registration->id,
                            'ticket_type_id' => $request->ttypes[$i]
                        ]);
                    for ($i = 0; $i < count($request->participant_question); $i++)
                        $answer = Answer::create([
                            'question_id' => $request->participant_question_id[$i],
                            'participant_id' => $participants[$i]->id,
                            'answer' => $request->participant_question[$i],
                        ]);
                }
                else{
                    $participant = Participant::create([
                        'name' => $request->name,
                        'surname' => $request->surname,
                        'email' => $request->email,
                        'registration_id' => $registration->id,
                        'ticket_type_id' => '1'
                    ]);
                }
    }

// storeRegistrationInfo() 现在是这样的:

public function storeRegistrationInfoF(Request $request, $id, $slug = null, Validator $validator){

        $allParticipants = Congress::where('id', $id)->first()->all_participants;

        if($allParticipants){
            $user = Auth::user();

            $rules = [
                'name' => 'required_unless:all_participants,0|max:255|string',
                'surname' => 'required_unless:all_participants,0|max:255|string',
                'email' => 'required_unless:all_participants,0|max:255|email',
                'participant_name.*' => 'required_unless:all_participants,0|max:255|string',
                'participant_surname.*' => 'required_unless:all_participants,0|max:255|string',
                'participant_email.*' => 'required_unless:all_participants,0|max:255|email',
            ];

            $messages = [
                'participant_question.*.required' => 'The participant is required'
            ];


            if($request->participant_question_required){
                foreach ($request->participant_question_required as $key => $value) {
                    $rule = 'string|max:255'; 

                    // if this was required, ie 1, prepend "required|" to the rule
                    if ($value) {
                        $rule = 'required|' . $rule;
                    }
                    $rules["participant_question.{$key}"] = $rule;
                }
            }

            $validator = Validator::make($request->all(), $rules, $messages);

            if($validator->passes()) {

                $registration = Registration::create([
                    'congress_id' => $id,
                    'main_user_id' => $user->id,
                    'status' => 'C',

                ]);

                if ($request->participant_name) {

                    $participants = [];

                    for ($i = 0; $i < count($request->participant_name); $i++)
                        $participants[] = Participant::create([
                            'name' => $request->participant_name[$i],
                            'surname' => $request->participant_surname[$i],
                            'email' => $request->participant_email[$i],
                            'registration_id' => $registration->id,
                            'ticket_type_id' => $request->ttypes[$i]

                        ]);
                }
            }

            return response()->json([
                'success' => true,
                'message' => 'success'
            ], 200);
        }
        else {
            $user = Auth::user();

            $registration = Registration::create([
                'congress_id' => $id,
                'main_user_id' => $user->id,
                'status' => 'C',

            ]);
            $participant = Participant::create([
                'name' => $user->name,
                'surname' => $user->surname,
                'email' => $user->email,
                'registration_id' => $registration->id,
                'ticket_type_id' => '1' // test
            ]);
        }
        $errors = $validator->errors();
        $errors =  json_decode($errors);

        return response()->json([
            'success' => false,
            'errors' => $errors
        ], 422);
    }

【问题讨论】:

  • 你得到什么样的错误?顺便说一句,如果您在问题中包含php 标签,代码将自动突出显示!我现在编辑了它,但很高兴知道
  • 如果参与者字段不是必需的,请将其替换为nullable,如果这些字段不是必需的。否则,检查这个问题,stackoverflow.com/questions/37777265/…
  • 谢谢,验证错误是姓名、姓氏和电子邮件是必填字段。
  • 参与者姓名和参与者姓氏不出现任何验证错误。
  • errors : {name: ["The name field is required."], surname: ["The surname field is required."],...} email : ["The email field is required." ] name : ["姓名字段为必填项。"] surname : ["姓氏字段为必填项。"]

标签: php laravel


【解决方案1】:

由于无论您的 $allParticipants 是否为 &gt; 0,您的验证始终要求您提供值,因此您需要确保 allParticipants 是否大于 0 以允许验证,否则跳过它。

public function storeRegistration(Request $request, $id, $slug = null, Validator $validator){
  // get your `$allParticipants` here
  if($allParticipants) {
    // put your logic here
  } else{
    // get the auth user
    // and register him if there is no particpants
    $user = Auth::user();
    $registration = Registration::create([
          'congress_id' => $id,
          'main_user_id' => $user->id,
          'status' => 'C',
    ]);
  }
});

您的函数需要如下所示:

公共函数 storeRegistrationInfoF(Request $request, $id, $slug = null, Validator $validator){

    $allParticipants = Congress::where('id', $id)->first()->all_participants;

    if($allParticipants){
        $user = Auth::user();

        $rules = [
            'name' => 'required_unless:all_participants,0|max:255|string',
            'surname' => 'required_unless:all_participants,0|max:255|string',
            'email' => 'required_unless:all_participants,0|max:255|email',
            'participant_name.*' => 'required_unless:all_participants,0|max:255|string',
            'participant_surname.*' => 'required_unless:all_participants,0|max:255|string',
            'participant_email.*' => 'required_unless:all_participants,0|max:255|email',
        ];

        $messages = [
            'participant_question.*.required' => 'The participant is required'
        ];


        if($request->participant_question_required){
            foreach ($request->participant_question_required as $key => $value) {
                $rule = 'string|max:255'; 

                // if this was required, ie 1, prepend "required|" to the rule
                if ($value) {
                    $rule = 'required|' . $rule;
                }
                $rules["participant_question.{$key}"] = $rule;
            }
        }

        $validator = Validator::make($request->all(), $rules, $messages);

        if($validator->passes()) {

            $registration = Registration::create([
                'congress_id' => $id,
                'main_user_id' => $user->id,
                'status' => 'C',

            ]);

            if ($request->participant_name) {

                $participants = [];

                for ($i = 0; $i < count($request->participant_name); $i++)
                    $participants[] = Participant::create([
                        'name' => $request->participant_name[$i],
                        'surname' => $request->participant_surname[$i],
                        'email' => $request->participant_email[$i],
                        'registration_id' => $registration->id,
                        'ticket_type_id' => $request->ttypes[$i]

                    ]);
            }

        return response()->json([
            'success' => true,
            'message' => 'success'
        ], 200);
      }
     if($validator->fails()) {
       $errors = $validator->errors();

       return response()->json([
        'success' => false,
        'errors' => $errors
       ], 422);
      }
    }
    else {
        $user = Auth::user();

        $registration = Registration::create([
            'congress_id' => $id,
            'main_user_id' => $user->id,
            'status' => 'C',

        ]);
        $participant = Participant::create([
            'name' => $user->name,
            'surname' => $user->surname,
            'email' => $user->email,
            'registration_id' => $registration->id,
            'ticket_type_id' => '1' // test
        ]);
    }
}

【讨论】:

  • 谢谢,但是即使 all_participants 为 0 也应该存在验证,以验证 name、surname 和 email 是否等于已验证用户的 name、surname 和 email 对吗?
  • 获取列值类似于“$allParticipants = Congress::where('id', $id)->first()->all_participants;”。那么放入 if($allParticipants) {...} 的代码是什么?是所有代码,除非规则 "$rules = [ 'name' => 'required|max:255|string', 'surname' => 'required|max:255|string', 'email' => 'required| max:255|email', 'participant_name.*' => 'required|max:255|string', 'participant_surname.*' => 'required|max:255|string', 'participant_email.*' => 'required |max:255|电子邮件', ];"?
  • 但是当 allParticipants 为 0 时,怎么可能进行注册呢?
  • 这是您在注册表中所做的,对吧?如果$allParticipants 不为空,则您的表单中只有字段。
  • 但是如果“all_participants”为0,区别在于用户不需要为每个参与者介绍信息,唯一需要的信息是认证用户的信息(姓名、姓氏和电子邮件),即是正在注册的用户
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-11
  • 2020-04-25
  • 2011-02-17
  • 1970-01-01
  • 2020-04-08
  • 2019-04-09
相关资源
最近更新 更多