【问题标题】:How to validate the field "questionOptions[]"? (it should be required, it should not be null)如何验证字段“questionOptions[]”? (它应该是必需的,它不应该为空)
【发布时间】:2019-01-22 20:50:54
【问题描述】:

我有一个页面供用户创建问题。为此,用户需要为问题和类型引入标题。要选择类型,有一个选择菜单:

<div class="form-group">
    <label for="type">Field type</label>
    <select class="form-control" name="type" id="customQuestionType">
        <option value="text">Text</option>
        <option value="long_text">Long Text</option>
        <option value="checkbox">Checkbox</option>
        <option  value="radio_btn">Radio button</option>
        <option  value="select_menu">Select menu</option>
        <option  value="file">FIle</option>
    </select>
</div>

如果用户选择类型选择菜单、复选框或单选按钮,他还需要引入该字段的选项。因此,如果用户选择了选择菜单、复选框或单选按钮的字段类型,默认情况下会出现 2 个字段,以便用户介绍选项的值:

<div class="form-group" id="availableOptions">
    <label for="inputName">Available Options</label>
    <div class="option">
        <input type="text" class="form-control col-md-8" name="questionOptions[]">
        <input type="button" class="removeOption btn btn-outline-primary col-md-3" value="Remove option"/>
    </div>
    <div class="option mt-3 d-flex justify-content-between">
        <input type="text" class="form-control col-md-8" name="questionOptions[]">
        <input type="button" class="removeOption btn btn-outline-primary col-md-3" value="Remove Option"/>
    </div>
</div>

疑问:我的疑问是关于如何验证 questionOptions 表单字段,因为如果用户选择复选框、选择菜单或单选按钮,用户至少应该引入 1 个选项输入的值,即是选项不能为空/空。所以在规则中我有“'questionOptions' => 'required'”。但是,如果用户没有为任何选项引入任何值,则会出现错误而不是验证消息:

SQLSTATE[23000]: Integrity constraint violation:
1048 Column 'value' cannot be null 
(SQL: insert into `question_options` 
(`question_id`, `value`, `updated_at`, 
`created_at`) values (8, , 2018-08-15 23:14:08, 2018-08-15 23:14:08)).

你知道问题出在哪里吗?

问题的存储方法:

public function store(Request $request, $id)
{
    $rules = [
        'question' => 'required',
        'type' => 'required|in:text,long_text,select_menu,radio_btn,file,checkbox',
        'questionOptions' => 'required'
    ];

    $customMessages = [
        'question.required' => 'The field title is required.',
        'type.required' => 'The field type is required.',
        'type.in' => 'Please introduce a valid type.',
        'questionOptions.required' => 'Please introduce the value at least for 1 option.',
    ];

    $this->validate($request, $rules, $customMessages);

    $congress= Congress::find($id);

    $question = Question::create([
        'congress_id' => $congress->id,
        'question' => $request->question,
        'type' => $request->type,
    ]);

    if (in_array($request->type, Question::$typeHasOptions)) {
        foreach ($request->input('questionOptions') as $questionOption) {
            QuestionOption::create([
                'question_id' => $question->id,
                'value' => $questionOption
            ]);
        }
    }

    Session::flash('success', 'Question created with success.');
    return redirect()->back();
}

【问题讨论】:

  • 进行自定义验证并检查是否通过了任何选项,如果没有跳过验证。

标签: php laravel


【解决方案1】:

您可以尝试自定义规则。像这样..

在提供者中编写自定义规则

public function boot()
{
    Validator::extend('check_empty', function ($attribute, $value, $parameters, $validator) {
        //your code to check if the value is empty in your way condition
        return check_array_empty_your_code($value)
    });

    //this is for custom message
    Validator::replacer('dns_email', function ($message, $attribute, $rule, $parameters) {
        return "Please introduce the value at least for 1 option.";
    });
}

然后提出请求类

class StoreRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
           'question' => 'required',
           'type' => 'required|in:text,long_text,select_menu,radio_btn,file,checkbox',
           'questionOptions' => 'required|check_empty'
        ]
    }

    public function messages()
    {
        return [
            'question.required' => 'The field title is required.',
            'type.required' => 'The field type is required.',
            'type.in' => 'Please introduce a valid type.',
            'questionOptions.required' => 'Value is required',
        ];
    }
}

然后在控制器中使用请求类

public function store(StoreRequest $request, $id)
{
    $congress= Congress::find($id);

    $question = Question::create([
        'congress_id' => $congress->id,
        'question' => $request->question,
        'type' => $request->type,
    ]);

    if (in_array($request->type, Question::$typeHasOptions)) {
        if (isset($request->questionOptions)) {
            foreach ($request->questionOptions as $questionOption) {
                QuestionOption::create([
                    'question_id' => $question->id,
                    'value' => $questionOption
                ]);
            } 
        } else {
            //return error
        }
    }

    Session::flash('success', 'Question created with success.');
    return redirect()->back();
}

【讨论】:

    【解决方案2】:

    要验证期望数组作为值的表单字段,例如 questionOptions[],您可以在验证规则和自定义消息中遵循此方法:

    $rules = [
        'question' => 'required',
        'type' => 'required|in:text,long_text,select_menu,radio_btn,file,checkbox',
        'questionOptions' => 'required|array',
        'questionOptions.*' => 'filled'
    ];
    
    $customMessages = [
        'question.required' => 'The field title is required.',
        'type.required' => 'The field type is required.',
        'type.in' => 'Please introduce a valid type.',
        'questionOptions.required' => 'Please introduce the value at least for 1 option.',
        'questionOptions.array' => 'Please introduce the value at least for 1 option.',
        'questionOptions.*.filled' => 'Please introduce the value at least for 1 option.'
    ];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-18
      • 2016-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多