如何验证字段“ questionOptions []”? (它是必需的,不能为null)

时间:2018-08-15 23:38:49

标签: php laravel

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

<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();
}

2 个答案:

答案 0 :(得分:0)

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

在提供程序中编写自定义规则

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();
}

答案 1 :(得分:0)

要像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.'
];