简体   繁体   English

Laravel验证JSON数据

[英]Laravel validate json data

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 $validation must be return true. 用户名和密码不为null,并且$validation必须返回true。 but return false 但返回假

Your var_dump shows the data you're trying to validate is inside a 'parameters' array. 您的var_dump显示您要验证的数据位于“参数”数组中。 You either need to change your rules to include the parameters, or you need to pass the parameters array to the validate method. 您或者需要更改规则以包含参数,或者需要将parameters数组传递给validate方法。

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);

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. 希望对您有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM