required_if Laravel 5验证 [英] required_if Laravel 5 validation

查看:367
本文介绍了required_if Laravel 5验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张表格,用户可以填写出售房屋的信息.对于其中一项投入,用户必须选择待售"或待租"天气.如果是For Sale,则会出现两个价格输入字段,如果是For Rent,则会基于jQuery出现其他一些价格输入字段.

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 Sale, two price input fields will appear, and if it is For Rent, then some other price input field will appear based off of jQuery.

我的问题是我希望填写价格字段,例如,如果我选择用于出租",然后提交表单,这将给我一个错误,指出用于出售"的价格字段即使在用于出租"部分下,该字段也是必填字段.

My problem is I want the price fields to be required, BUT for example if I'am selecting "For Rent", and then I submit my form, it will give me an error saying the price fields for the "For Sale" input fields are required, even though it is under the "For Rent" section.

我知道Laravel中有一个 required_if ,但是我只是不知道如何利用它.这是我的财产要求.

I know there is a required_if in Laravel, but I just dont know how to utilize that. Here is my Requests for a Property.

<?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',   
        ];
    }
}

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

/****************** EDIT ***************************/

我现在所拥有的:

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

但是我提交表单时收到此错误:

But I get this error when I submit the Form:

推荐答案

假定list_type是选择框的名称(值:出售或出租)

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

以这种方式使用

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

这是什么意思? :

仅当list_type的值等于selling

the sale price is only required if the value of list_type is equal to 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'
}

这篇关于required_if Laravel 5验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆