Frnak
Frnak

Reputation: 6792

Form Request Validation JSON

I'm trying to validate that an input is valid json. However it returns success for "123" as input. This does not seem to be valid or at least is not valid in terms of what i need.

Do you know a way to improve the validation for json input?

public function rules()
{
    switch($this->method()) {
        case "GET":
            return [];
        case "DELETE":
            return [];
        default:
            return [
                'name' => 'required',
                'templatestring'  => 'required|JSON'
            ];
    }
}

Upvotes: 1

Views: 976

Answers (1)

Luís Cruz
Luís Cruz

Reputation: 14970

123 is a valid JSON based on the newer RFC 7159.

If you're trying to validate a JSON string based on the RFC 4627, you should probably use the regex validation rule. For example:

$data = [
    'name'           => 'test',
    'templatestring' => '123'
];

$validator = Validator::make($data, [
    'name'           => 'required',
    'templatestring' => 'required|regex:/[^,:{}\\[\\]0-9.\\-+Eaeflnr-u \\n\\r\\t]/'
]);

// With `123` this returns true (as it fails).
// If you set $data['templatestring'] = '{"test": 123}' this returns false.
return $validator->fails();

The regex was taken from this answer.

Upvotes: 3

Related Questions