2016-10-10 128 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

非常感谢! –