laravel 如何验证单选按钮/复选框并且必须在laravel中选择一个

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30624920/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:42:40  来源:igfitidea点击:

How to validate radio button/checkbox and must to select one in laravel

phpvalidationlaravelradio-button

提问by Giang

I'm trying to validate a radio button in Laravel. This is my code, but it doesn't work.

我正在尝试验证 Laravel 中的单选按钮。这是我的代码,但它不起作用。

In my case, i have a dynamicform with many questions with different of type such as : radio, checkbook, single input, number input,... So I have to use array name for each type of question. For example : name="radio['.$k.']".

就我而言,我有一个动态表单,其中包含许多不同类型的问题,例如:收音机、支票簿、单一输入、数字输入……所以我必须为每种类型的问题使用数组名称。例如:name="radio['.$k.']"。

In my controller i make validation and $key is the $k value in initial form.

在我的控制器中,我进行了验证,$key 是初始形式的 $k 值。

public function rules()
{
 $rules = [];
if (Input::has('radio')) {
    foreach (Input::get('radio') as $key => $val) {
        $rules['radio.' . $key] = 'required';
    }
 }
if (Input::has('singleinput')) {
            foreach (Input::get('singleinput') as $key => $val) {
                $rules['singleinput.'.$key] = 'required|max:10';
                }
            }

}

 public function messages()
    {
        $messages = [];

        if (Input::has('radio')) {
      // some code here;
         }
     }

public function answer_store($survey_id, $patient_id)
    {
        $rule = $this->rules();
        $message = $this->messages();
        $validator = Validator::make(Input::all(), $rule, $message);
}

In the view:

在视图中:

<input type="radio" name="radio['.$k.']" value="'.$str1.'">'.$answer->answer_body

My code works with text input type but not with radio & checkbox. Anyone can help me?

我的代码适用于文本输入类型,但不适用于收音机和复选框。任何人都可以帮助我吗?

回答by Chris Townsend

Okay with no reply, this is my answer if you are using Laravel 5.

好的,没有回复,如果您使用的是 Laravel 5,这就是我的答案。

Laravel 5 uses requests when you submit a form. You can perform validation on that data before it executes your controller.

Laravel 5 在您提交表单时使用请求。您可以在执行控制器之前对该数据执行验证。

Firstly use your terminal to run a artisan command

首先使用您的终端运行工匠命令

php artisan make:request MyRequest

This will create a file in App\Http\Requests.

这将在 App\Http\Requests 中创建一个文件。

Put this in the new request file

把它放在新的请求文件中

<?php namespace App\Http\Requests;

use App\Http\Requests\Request;

class MyRequest 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 [
            'myRadios' => 'required'
        ];
    }

}

In your view, have radios like the following, ensuring the group of radios you want all have the same name.

在您看来,拥有如下所示的收音机,确保您想要的收音机组都具有相同的名称。

<input type="radio" name="myRadios" value="1"> Number 1
<input type="radio" name="myRadios" value="2"> Number 2
<input type="radio" name="myRadios" value="3"> Number 3

In your Controller you will need to reference the request file and put it into your function using dependency injection.

在您的控制器中,您需要引用请求文件并使用依赖注入将其放入您的函数中。

When you want to use the value of the radio that was selected, you use the $request array

当你想使用被选中的收音机的值时,你使用 $request 数组

<?php namespace App\Http\Controllers;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use Illuminate\Http\Request;
use App\Http\Requests\MyRequest;

class MyController extends Controller {

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function myFormFunction(MyRequest $request)
    {
        //Get the value of the radio selected
        $myVariable = $request['myRadios'];
    }

}

?>

回答by Giang

After one day, I found the solution for my problem.

一天后,我找到了解决问题的方法。

Using if (Input::has('radio')) { } in the rule code. Because if i don't select anything, don't have any information related radio to validate.

在规则代码中使用 if (Input::has('radio')) { } 。因为如果我不选择任何东西,就没有任何与无线电相关的信息来验证。

For array of radio questions I use:

对于我使用的一系列无线电问题:

<input type="radio" name="radio['.$count_radio.']" value="'.$str1.'">

My problem is i don't know how many radio question each form. I have many different form. I will count number of radio form in View file and pass to Controll ($count_radio).

我的问题是我不知道每个表格有多少无线电问题。我有很多不同的形式。我将计算视图文件中无线电表单的数量并传递给 Controll ($count_radio)。

In controller, i make rule like this:

在控制器中,我制定了这样的规则:

for ($key = 1; $key <= $count_radio; $key++) {
            $rules['radio.' . $key] = 'required';
        }

I also add error with this code in View:

我还在视图中使用此代码添加错误:

       if($errors->has('radio.'.$count_radio.'')) {
            echo $errors->first('radio.'.$count_radio.'');
       }

That's all.

就这样。

回答by andylondon

You have the input tag ending in </label>. Not sure if that will help.

您的输入标签以</label>. 不确定这是否会有所帮助。