2016-10-10 116 views
1

我想驗證輸入是否有效json。但是,它返回「123」作爲輸入的成功。這似乎不是有效的,或者至少在我所需要的方面是無效的。表單請求驗證JSON

你知道一種改進json輸入驗證的方法嗎?

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

就有關PHP而言,'123' *是有效的JSON。 'json_decode('123')'或者試試http://jsonlint.com/。 – ceejayoz

回答

2

123是一個基於新RFC 7159一個有效的JSON。

如果您嘗試驗證基於RFC 4627的JSON字符串,則應該使用regex驗證規則。例如:

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

該正則表達式取自this answer

+0

非常感謝! –