如何在laravel上进行良好的验证?

问题描述 投票:0回答:1

我有数据,它们看起来像这样:

 {
   sender_name : "Real fake sender name",
   recipient_name : "Real fake recipient name",
   goods: [
     {
        "no" : 1
        "name":"Pen",
        "unit": "1",
        "qty":"50",
        "price":"50",
        "amount":"2500",
        "vat_percent":"5",
        "vat_sum": "125",
        "total_sum": "2625"
     }
   ]
 }

我需要使用扩展验证器来验证“商品”。这是他的代码:

Validator::extend('invoiceGoods' , function($attribute, $value, $parameters, $validator) {

  $rulesForGoods = [
      'no'          => 'integer|required',
      'name'        => 'string|max:64|required',
      'unit'        => 'required|integer',
      'qty'         => 'required|string',
      'price'       => 'required|numeric',
      'amount'      => 'required|numeric',
      'vat_percent' => 'nullable|numeric',
      'vat_sum'     => 'nullable|numeric',
      'total_sum'   => 'required|numeric'
  ];

  foreach ($value as $good) {
      $validator = Validator::make($good , $rulesForGoods);
      if ($validator->fails()) {
          return false;
      }
  }

  return true;

});

这是主要代码。

$validator = Validator::make($data , [
   'goods' => 'invoiceGoods',
   'sender_name' => 'string',
   'recipient_name' => 'string',
]);

if ($validator->fails()) {
  return response()->json([
    'success' => false,
    'message' => 'Validation error.',
    'data'    => $validator->errors()
  ]);
}

如果发生商品验证错误,我将得到以下答案:

enter image description here

但是我想显示这样的错误:商品中没有1的错误单位。

我知道第三个参数可以传递带有自定义消息的数组,但是如果它应该返回true或false,如何从扩展验证器返回它?

laravel laravel-validation
1个回答
1
投票

https://laravel.com/docs/5.8/validation#custom-error-messages

$messages = [
'Validation.invoice_goods' => 'Errror message!',];

$validator = Validator::make($input, $rules, $messages);
© www.soinside.com 2019 - 2024. All rights reserved.