2016-06-12 125 views
10

我有一个表格,用户可以填写出售他们的家。对于其中一个输入,用户必须选择“待售”或“出租”的天气。如果是“待售”,则会出现两个价格输入字段,如果是“出租”,则会基于jQuery显示其他一些价格输入字段。required_if Laravel 5验证

我的问题是我想要的价格字段是必需的,但例如,如果我选择“出租”,然后我提交我的表单,它会给我一个错误说价格字段为“For销售“输入字段是必需的,即使它在”出租“部分。

我知道在Laravel有required_if,但我只是不知道如何利用它。这是我对物业的要求。

<?php 

namespace App\Http\Requests; 

use App\Http\Requests\Request; 

class PropertyRequest 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 [ 
      'list_type' => 'required', 
      'sale_price' => 'required', // <-- maybe like: required_if:value 
      'rent_price' => 'required', 
     ]; 
    } 
} 

/******************编辑*********************** ****/

我现在拥有的一切:

public function rules() 
    { 
     return [ 
      'list_type' => 'required', 
      'sale_price' => 'required_if:list_type:For Sale', 
      'rent_price' => 'required_if:list_type:For Rent', 
    } 

但是,当我提交表单我得到这个错误:

My Error

回答

25

假设LIST_TYPE是选择的名字框到c hoose从(值:出售或出租)

使用这种方式

"sale_price" => "required_if:list_type,==,selling" 

这是什么意思?

的销售价格仅在需要LIST_TYPE的值等于selling

rent_price

编辑

public function rules() 
{ 
    return [ 
    'list_type' => 'required', 
    'sale_price' => 'required_if:list_type,==,For Sale', 
    'rent_price' => 'required_if:list_type,==,For Rent' 
} 
+0

一样做同样在这个职位上,我在下面编辑它。 – David

+0

检查我的编辑,现在尝试了一个错误,如果这不起作用,请添加==,就像这个'sale_price“=>”required_if:list_type,==,出售“' –

+1

您的**编辑**部分谢谢。 – David