php – Laravel只验证发布的项目并忽略其余的验证数组

php – Laravel只验证发布的项目并忽略其余的验证数组,第1张

概述对于使用Laravel 4.1的项目,我有一个我想要解决的UI问题. 一些输入在模糊时对laravel进行ajax调用,并且工作正常.它只是发送它的价值.在laravel我然后检查验证器. public function validate() { if(Request::ajax()) { $validation = Validator::make(Inpu 对于使用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 valuesforeach ($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数组中的可选字段 – 只有在提交数据中存在该字段时才会使用可选字段.

总结

以上是内存溢出为你收集整理的php – Laravel只验证发布的项目并忽略其余的验证数组全部内容,希望文章能够帮你解决php – Laravel只验证发布的项目并忽略其余的验证数组所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1256700.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-07
下一篇2022-06-07

发表评论

登录后才能评论

评论列表(0条)

    保存