Laravel 验证 json 数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27257165/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 10:30:13  来源:igfitidea点击:

Laravel validate json data

phpjsonlaravellaravel-4laravel-validation

提问by

in this code i'm try to validate json data but validater return false

在这段代码中,我尝试验证 json 数据,但验证器返回 false

        $username = $data['username'];
        $password = $data['password'];

        $input = Input::json();
        $rules = array(
            'username' => 'required',
            'password' => 'required',
        );
        $input_array = (array)$input;
        $validation = Validator::make($input_array, $rules);
        if ($validation->fails()) {
            var_dump( $input_array );
        }else {
                $result = array('code'=>'3');
            }

var_dump result is :

var_dump 结果是:

array(1) {  ["parameters"]=>  array(3) {    ["password"]=>    string(9) "world"    ["username"]=>    string(1) "hello"    ["function"]=>    string(8) "register"  }}""

username and password is not null and $validationmust be return true. but return false

用户名和密码不为空,$validation必须返回真。但返回假

回答by patricus

Your var_dump shows the data you're trying to validate is inside a 'parameters' array. You either need to change your rules to include the parameters, or you need to pass the parameters array to the validate method.

您的 var_dump 显示您尝试验证的数据位于“参数”数组内。您要么需要更改规则以包含参数,要么需要将参数数组传递给验证方法。

Option 1 - change your rules:

选项 1 - 更改规则:

$rules = array(
    'parameters.username' => 'required',
    'parameters.password' => 'required',
);
$input_array = (array)$input;
$validation = Validator::make($input_array, $rules);

Option 2 - validate the data in the parameters array:

选项 2 - 验证参数数组中的数据:

$rules = array(
    'username' => 'required',
    'password' => 'required',
);
$input_array = (array)$input;
$validation = Validator::make($input_array['parameters'], $rules);

回答by madSkillz

Here is a method that has worked for me.

这是一种对我有用的方法。

$InputData = array('username' =>Input::json('username'),
                    'password'=>Input::json('password'));

$validation = Validator::make( $InputData,array('username'=>'required|email','password'=>'required'));

Hope you find it usefull.

希望你觉得它有用。