required_if Laravel 5 validation

前端 未结 4 1348
悲&欢浪女
悲&欢浪女 2020-12-02 22:11

I have form that a user can fill-out for selling their home. And for one of the in puts, a user must select weather it will be \"For Sale\" or \"For Rent\". If it is For Sal

相关标签:
4条回答
  • 2020-12-02 22:44

    There can be another situation when, the requirement will be required if another field is not present, if someone is in this situation, you can do

    'your_field.*' => 'required_unless:dependency_field.*,
    
    0 讨论(0)
  • 2020-12-02 22:50

    You could also use the Illuminate\Validation\Rules\RequiredIf rule directly.

    Note: This rule is available in Laravel 5.6 and up.

    class SomeRequest extends FormRequest
    {
        ...
        public function rules()
        {
            return [
                'sale_price' => new RequiredIf($this->list_type == 'For Sale'),
                'rent_price' => new RequiredIf($this->list_type == 'For Rent'),
            ];
        }
    }
    
    

    And if you need to use multiple rules, then you can pass in an array.

    public function rules()
    {
        return [
            'sale_price' => [
                new RequiredIf($this->list_type == 'For Sale'),
                'numeric', 
                'string',
                ...
            ]
        ];
    }
    
    
    0 讨论(0)
  • 2020-12-02 22:55

    assuming that list_type is the name of the select box to choose from (values : selling or rent)

    use it this way

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

    what does this mean? :

    the sale price is only required if the value of list_type is equal to selling

    do the same for rent_price

    edit

    public function rules()
    {
      return [
       'list_type'  => 'required',
       'sale_price' => 'required_if:list_type,==,For Sale',
       'rent_price' => 'required_if:list_type,==,For Rent'
    }
    
    0 讨论(0)
  • 2020-12-02 23:07

    You can use Illuminate\Validation\Rule in Laravel as given below to build the validator.

    $validator =  Validator::make( $request->input(), [
        'list_type' => 'required',
        'sale_price'=> Rule::requiredIf( function () use ($request){
            return $request->input('list_type') == 'For Sale';
        }),
        'rent_price'=> Rule::requiredIf( function () use ($request){
            return $request->input('list_type') == 'For Rent';
        }),
    ]);
    
    0 讨论(0)
提交回复
热议问题