在laravel 5中,我发出了一个名为ApiRequest
的新请求。
class ApiRequest extends Request
{
public function authorize() {
return $this->isJson();
}
public function rules()
{
return [
//
];
}
}
如你所见,我只接受json数据。而我正在接收控制器中的json
public function postDoitApi(ApiRequest $payload) {
$inputJson = json_decode($payload->getContent());
$name = $inputJson->name;
}
哪个工作正常。我正在$name
中获取数据。但现在我需要验证输入json。
我需要在ApiRequest
中为name
密钥设置验证规则,如此
public function rules()
{
return [
'name' => 'required|min:6'
];
}
帮我这样做。感谢。
答案 0 :(得分:2)
Laravel以同样的方式验证AJAX请求。只需确保您在请求中设置其中一个请求标头:
'Accept': 'application/json'
'X-Requested-With': 'XMLHttpRequest'
答案 1 :(得分:1)
您可以使用验证方法而不是规则方法:
class ApiRequest extends Request
{
public function authorize() {
return $this->isJson();
}
public function validator(){
//$data = \Request::instance()->getContent();
$data = json_decode($this->instance()->getContent());
return \Validator::make($data, [
'name' => 'required|min:6'
], $this->messages(), $this->attributes());
}
//what happens if validation fails
public function validate(){
$instance = $this->getValidatorInstance();
if($this->passesAuthorization()){
$this->failedAuthorization();
}elseif(!$instance->passes()){
$this->failedValidation($instance);
}elseif( $instance->passes()){
if($this->ajax())
throw new HttpResponseException(response()->json(['success' => true]));
}
}
}
答案 2 :(得分:0)
return $inputJson->toArray();
然后传递给验证器
$name = ['name'=>'er'];
$rules = array('name' => 'required|min:4');
$validation = Validator::make($name,$rules);
答案 3 :(得分:0)
您可以在ApiRequest
表单请求中添加以下功能。
public function validator(){
return \Validator::make(json_decode($this->getContent(),true), $this->rules(), $this->messages(), $this->attributes());
}
答案 4 :(得分:0)
可以通过两个步骤以干净的方式验证任何标头:
prepareForValidation
方法中请求数据。public function prepareForValidation()
{
$this->merge([
"content_type" => $this->headers->get("Content-type"),
]);
}
application/json
。所以public function rules(): array
{
return [
"content_type" => "required|in:application/json",
];
}
完整示例如下:
/**
* Class LoginRequest
*
* @package App\Requests
*/
class LoginRequest extends FormRequest
{
public function prepareForValidation()
{
$this->merge([
"content_type" => $this->headers->get("Content-type"),
]);
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules(): array
{
return [
"content_type" => "required|in:application/json",
];
}
}