对于使用Laravel 4.1的项目,我有一个我想要解决的UI问题.
一些输入在模糊时对laravel进行ajax调用,并且工作正常.它只是发送它的价值.在laravel我然后检查验证器.
public function validate() { if(Request::ajax()) { $validation = Validator::make(Input::all(),array( 'email' => 'unique:users|required|email','username' => 'required' )); if($validation->fails()) { return $validation->messages()->toJson(); } return ""; } return ""; }
虽然这有效,但json字符串还包含我无需检查的字段.确切地说,这是我得到的反馈:
{"email":["The email field is required."],"username":["The username field is required."]}
但看到它是模糊的我只想要一个我实际检查的那个.所以,如果我模糊电子邮件,我希望返回:
{"email":["The email field is required."]}
现在我知道这显然是因为我的数组包含多个字段,但我不想为我曾经做过的每个可能的输入编写完整的验证.
我的问题是:我能以某种方式只获得实际发布的post值的返回值,即使该值可能为null并且不能返回其余的数组.
解决方法
试试这个(未经测试,如果不起作用,请随时评论/ downvote):
// required rules,these will always be present in the validation $required = ["email" => "unique:users|required|email","username" => "required"]; // Optional rules,these will only be used if the fields they verify aren't empty $optional = ["other_field" => "other_rules"]; // Gets input data as an array excluding the CSRF token // You can use Input::all() if there isn't one $input = Input::except('_token'); // Iterates over the input values foreach ($input as $key => $value) { // To make field names case-insensitive $key = strtolower($key); // If the field exists in the rules,to avoid // exceptions if an extra field is added if (in_array($key,$optional)) { // Append corresponding validation rule to the main validation rules $required[$key] = $optional[$key]; } } // Finally do your validation using these rules $validation = Validator::make($input,$required);
将所需字段添加到$required数组,键是POST数据中字段的名称,以及$optional数组中的可选字段 – 只有在提交数据中存在该字段时才会使用可选字段.