簡體   English   中英

帶有請求類的自定義驗證規則不工作 laravel 7

[英]Custom validation rule with request class not working laravel 7

下面是我的代碼;

水果請求.php

class FruitRequest extends Request
{

public function authorize()
{
    return true;
}

public function rules()
{
    return [
        'name' => 'required|alpha',
        'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048'
    ];
}

public function messages()
{
    return ['name.required' => response("Name should be mandatory", 404),
        'name.alpha' => response("Name should be contains only letters", 404),
        'image.required' => response("Foto should be mandatory", 404),
        'image.mimes' => response('Foto should be jpeg,png,jpg,gif,svg', 404),
        'image.max' => response('Foto size should be blow 2 MB', 404),
    ];
}

}

水果控制器.php

use App\Http\Controllers\Controller;
use App\Http\Requests\FruitRequest;

class FruitController extends Controller
{

public function store(FruitRequest $request)
{
    echo $request->input('name');

    //above line gives nothing to me
}

}

如果我使用extends Request而不是extends FruitRequest那么這給了我由用戶在郵遞員中傳遞的值。 我不知道為什么這個自定義請求類不起作用。我附上了截圖。 請幫忙....

在此處輸入圖片說明

很長時間不使用郵遞員了,我正在用我的代碼進行測試

我正在使用 FormRequest 像這樣:

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;

class YourRequest extends FormRequest
{
  //this function called if Validator::make()->fails();
  //here where you can modifying your message
  protected function failedValidation(Validator $validator)
  {
    //note this only for API, for formData use \Illuminate\Validation\ValidationException($validator)
    throw new HttpResponseException(response()->json($validator->errors()->all(), 422));
    //this will get parameter attribute set from FormRequest
    //attributes() along with the error message, 
    //or $validator->errors()->all() to get messages only like my screenshot
    //or modify message with your logic
  }

  public function authorize() { return true; }
  public function rules() { return []; }
  public function attributes() { return []; }
  public function messages() { return []; }
}

在控制器中:

use YourRequest;

public function store(YourRequest $req)
{
  return response($req->all())->setStatusCode(200); 
}

在您的 FormRequest 替換 response() 中,只需文本:

public function messages()
{
    return ['name.required' => "Name should be mandatory"],
}

2,驗證alpha只接受字母,你的名字是數字,結果來自我的代碼(我使用默認的驗證器消息,在消息數組中): 郵差

使用 FormRequest 擴展您的請求類

use Illuminate\Foundation\Http\FormRequest;

class FruitRequest extends FormRequest

有關更多詳細信息,請訪問 laravel 的官方文檔: https ://laravel.com/docs/7.x/validation#creating-form-requests

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM