如何在laravel中使用一个请求文件验证多个表单?

时间:2017-10-03 04:10:18

标签: laravel laravel-5

我有三个表单,我想在一个请求文件中验证它们。如何检查规则方法中的表单标识。我很困惑。我写了这个,但它没有工作。这是我的代码

 //rules method
    public function rules()
 {

   switch ($this->check())
    {
        case 'personal':
            return ['fanme'=>'required'];
            break;

        case 'career':
            return ['career'=>'required'];
            break;  

        case 'summary':
            return ['summary_info'=>'required'];
            break; 

        default:
             return [];
            break;
   }
}


//my own method
public function check()
 {
  return $this->input('form_identity');
 }
//form field
<input type="hidden" value="personal" 
 class="form-control required" 
 name="form_identity"/>

2 个答案:

答案 0 :(得分:0)

您没有提到为什么您现有的代码无法正常工作,但您有正确的想法。保持简单:

public function rules() {
    switch ($this->form_identity) {
        case 'personal':
            $rules = ['fanme'=>'required'];
            break;
        case 'career':
            $rules = ['career'=>'required'];
            break;
        case 'summary':
            $rules = ['summary_info'=>'required'];
            break;
        default:
            $rules = [];
    }

    return $rules;
}

您可以在表单请求(Request)中访问完整的$this,这样您就可以测试请求中的任何可用内容 - 例如输入值,方法(POST,{ {1}}等),经过身份验证的状态等。

答案 1 :(得分:0)

您可以使用在表单输入中添加唯一标识符的表单输入

public function rules()
{
    $data = request()->all();
    $serviceName = isset($data['serviceName'])?$data['serviceName']:'';

   // IF it is API CALL, you can use header
   // $serviceName = request()->header('serviceName');

    switch ($serviceName) {
        case 'userRegister':
            $rules = [ 
                'serviceName' => 'required',
                'firstname' => 'required|regex:/^[a-zA-Z ]+$/u|max:36',
                'lastname' => 'required|regex:/^[a-zA-Z ]+$/u|max:36',
                'email' => 'required|string|email|max:255|unique:users',
                'password' => 'required|string|min:6|confirmed'
            ];
            break;
        case 'codeVerify':
            $rules = ['activation_code'=>'required'];
            break;
        case 'summary':
            $rules = ['summary_info'=>'required'];
            break;
        default:
            $rules = ['serviceName' => 'required',];
    }
    return $rules;
}