【问题标题】:Form validation in select field选择字段中的表单验证
【发布时间】:2019-10-23 10:50:52
【问题描述】:

有没有一种方法可以检查用户是否没有操作表单?在我的表单中,我得到了所有可用的条目,但是如果用户在浏览器中更改值 id,我只会得到一个错误。任何提示:)?

<div class="form-group-row club col-lg-10">
    <label>Choose Product</label>
    <select name="product_id" class="form-control" required>
    @foreach($products as $product)
        <option value="{{$product->id}}">{{$product-> product}}</option>
    @endforeach
    </select>
</div>

【问题讨论】:

标签: php laravel forms validation


【解决方案1】:

您可以使用规则来验证接收到的数据,例如:

use Illuminate\Validation\Rule;

Validator::make($data, [
    'product_id' => [
        'required',
        Rule::in([/*array of products ids here*/]),
    ],
]);

看看https://laravel.com/docs/5.8/validation#rule-in

你可以像这样使用存在:

Validator::make($data, [
    'product_id' => [
        'required',
        'exists:table_name,column_name'
    ],
]);

【讨论】:

  • 或在products 表或任何表上使用exists 规则?
  • 问题是,用户可以根据需要创建更多类别。但我会阅读文档。 tyvm :)
  • 创建它们并同时使用它们会产生问题,但是如果它们存储在数据库中,那么您可以在[/*array of products ids here*/]部分中阅读它们
【解决方案2】:

你可以选择只读

<select name="product_id" class="form-control" required readonly>

但用户可以通过 devtools 更改 html

你也可以像这样在后端检查它

if ($products->pluck('id')->diff(request()->input('product_id'))->empty()) {
    //not changed
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-17
  • 1970-01-01
  • 2012-05-12
  • 2012-05-23
  • 2019-05-19
  • 2021-05-21
相关资源
最近更新 更多