1. 程式人生 > >laravel ajax驗證支援,返回json錯誤資訊

laravel ajax驗證支援,返回json錯誤資訊

改造request驗證類,新增failedValidation方法:

<?php

namespace App\Http\Requests\Index;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\JsonResponse;
class CommunityRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        switch($this->path()){
            case 'community/store':
                return [
                            'name'=>'required|max:200',
                            'email'=>'required|max:200',
                            'facebook'=>'max:200',
                            'twitter'=>'max:200',
                            'remark'=>'max:20000'
                        ];
        }
        
    }

        public function messages(){
            return [
                'name.required' => 'Please type in your name !',
                'email.required' => 'Please type in your email !',
        
    ];
        
    }
    
    public function failedValidation(Validator $validator) {
        exit(json_encode(array(
            'code' => 403,
            'info' => $validator->getMessageBag()->first()
        )));
    }
}