user4001049
user4001049

Reputation:

Laravel validate json data

in this code i'm try to validate json data but validater return 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 :

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. but return false

Upvotes: 2

Views: 9078

Answers (2)

madSkillz
madSkillz

Reputation: 37

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.

Upvotes: 1

patricus
patricus

Reputation: 62228

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.

Option 1 - change your rules:

$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:

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

Upvotes: 2

Related Questions