【问题标题】:Laravel if Checkbox value true, Price is RequiredLaravel 如果复选框值为真,价格是必需的
【发布时间】:2018-07-09 09:05:48
【问题描述】:

我的刀片中有一个复选框,用户可以在其中启用其他付款方式,现在我希望如果有人选中此框,则此付款方式需要价格。

复选框刀片

<div class="form-group">
    <label for="accept1">
        <img src="/img/accept1.png">
        Accept other payment method
    </label>
    <input type="checkbox" value="true" name="accept1"> Yes
</div>

价格刀片

<div class="form-group">
    <label for="newprice"><img src="/img/newprice.png"> New</label>
    <input type="number" step="any" name="newprice" value="{{old('newprice')}}">
</div>

控制器

<?php

if ($request->accept1 == 'true') {
    $product->accept1 = true;
}

if ($request->newprice == 'true') {
    if (!is_numeric($request->newprice) || $request->newprice <= 0.0001) {
        session()->flash('errormessage', ' Price is required');
        return redirect()->back()->withInput();
    }
}

如果有人现在点击复选框,他们还必须输入价格,否则会收到错误消息。

如何更改代码以使其正常工作?

【问题讨论】:

  • Laravel blade check box的可能重复
  • 那帮不了我..
  • Laravel 文档有一个 huge section on validation - 我强烈建议您查看那里的代码示例,因为看起来您甚至没有利用其强大且极其方便的请求验证和输入错误处理。您正在寻找的是 required_if 验证规则。

标签: php laravel laravel-5


【解决方案1】:

试试下面的代码:

  If($request->accept1 === true){

            Validator::make($request->all(), [
                   "newprice" =>"required"
                  ],["newprice.required"=>"message"]);
     }

【讨论】:

    【解决方案2】:

    您可以使用如下的 laravel 验证规则:

    $validator = Validator::make($request->all(), [
            "newprice" =>"required_if:accept1,==,true|numeric|min:0.0001"
        ]); 
    
    
    if ($validator->fails()) {
            return redirect()->back()
                        ->withErrors($validator)
                        ->withInput();
        }
    

    https://laravel.com/docs/5.5/validation

    【讨论】:

      【解决方案3】:

      你可以使用 Laravel 表单验证来做到这一点。

      来自docs

      required_if:anotherfield,value,...

      valida 下的字段你可以使用 Laravel Form validation 来做到这一点:tion 必须存在且不能为空,如果 另一个字段字段等于任何值。

      试试:

      $request->validate([
          'newprice' =>  'required_if:accept1,==,true',
      ]);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-10-04
        • 2011-01-09
        • 2023-03-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-03
        • 1970-01-01
        相关资源
        最近更新 更多