Laravel使用自定义消息验证动态添加的输入

时间:2018-11-19 02:34:08

标签: php laravel

我正在使用laravel开发库存系统。

一切都按预期进行,直到即时表单验证出现问题。

下面是我的订单控制器代码中的插入函数,

public function insert(Request $request) {
    // Save data to "orders" table
    $orderer = [
      'orderId' => $request->get('orderId'),
      'customerId' => $request->get('customerId'),
      'orderTotal' => $request->get('orderTotal'),
      'paymentMethodId' => $request->get('paymentMethodId'),
      'orderStatusId' => $request->get('orderStatusId'),
      'created_at' =>  \Carbon\Carbon::now(), # \Datetime()
      'updated_at' => \Carbon\Carbon::now()  # \Datetime()
    ];

    // Looping on dynamic "New Added" input field
    $orderedItems_Sku = $request->get('productSku');
    foreach($orderedItems_Sku as $key => $v)
    {
      $productSku = $request->get('productSku') [$key];
      $product = \App\Product::find($productSku);
      $rules = [
              'orderId' => 'unique:orders',
              'customerId' => 'required',
              'orderStatusId' => 'required',
              'paymentMethodId' => 'required',
              'uomId.*' => 'required',
              'productSku.*' => 'required',
              'productQty.*' => 'required',
              // 'lte' means Less Than or Equal to available stock quantity
              'orderQty.*' => 
              'required|numeric|min:1|lte:'.$product['productQty'],
              'orderPrice.*' => 'required'
          ];

      $messages = [
                'customerId.required' => 'Please select Customer',
                'orderStatusId.required' => 'Please select Order Status',
                'paymentMethodId.required' => 'Please select Payment Method',
                'uomId.*.required' => 'Please select UOM',
                'productSku.*.required' => 'Please select Product',
                'orderQty.*.required' => 'Please enter Order Quantity',
                'orderQty.*.min' => 'Quantity must be at least 1',
                'orderQty.*.lte' => 'Quantity of product no. 
                '.$product['productSku'].' must be not greater than 
                '.$product['productQty'],
                'orderPrice.*.required' => 'Please enter Product Price'
          ];

      // Validate "Rules" and "Messages" to running.
      $this->validate($request, $rules, $messages); 

      $data = [
        'orderId' => $request->get('orderId'),
        'productSku' => $v,
        'orderQty' => $request->get('orderQty') [$key],
        'uomId' => $request->get('uomId'),
        'orderPrice' => $request->get('orderPrice') [$key],
        'orderDiscount' => $request->get('orderDis') [$key],
        'orderPerAmount' => $request->get('orderPerAmount') [$key],
        'created_at' =>  \Carbon\Carbon::now(), # \Datetime()
        'updated_at' => \Carbon\Carbon::now()  # \Datetime()
      ];
      \App\orderedItem::insert($data);
      // "Decrement" means, product quantity will be deducted based on how 
      much quantity that customer has ordered.
      \App\Product::where("productSku", $v)->decrement("productQty", 
      $request->orderQty [$key]);
    }
    \App\Order::insert($orderer);
    return redirect('orders')->with('success', 'Order Successfully Added!'); 
  }

这是我在create.blade.php中的html代码,

https://pastebin.com/cn2X1aVL

如您所见,有“ orderQty”和“ productQty”字段。

因此,我试图通过动态“ productQty”字段验证动态“ orderQty”字段,以防止用户在“ productQty”字段中输入大于值的数量。

我还按照大多数laravel社区的建议,在我的代码的$ rules数组内使用了lte(小于等于)命令。

这件事仅对单个输入有效,而对动态添加的输入无效。请参阅下面的图片,您可以看到,该产品的第二个输入未按照我的要求正确验证。

create blade file

甚至错误消息也没有按要求显示动态消息。

请帮助我找出问题所在。我尝试了很多解决方案,但仍然无法正常工作。 :'(

3 个答案:

答案 0 :(得分:2)

在测试了答案提出的所有可能的解决方案之后,

现在固定了!

这是我在OrderController中的插入函数代码,

public function insert(OrderRequest $request) {
    // Save data to "orders" table
    $orderer = [
      'orderId' => $request->get('orderId'),
      'customerId' => $request->get('customerId'),
      'orderTotal' => $request->get('orderTotal'),
      'paymentMethodId' => $request->get('paymentMethodId'),
      'orderStatusId' => $request->get('orderStatusId'),
      'created_at' =>  \Carbon\Carbon::now(), # \Datetime()
      'updated_at' => \Carbon\Carbon::now()  # \Datetime()
    ];

    // Looping on dynamic "New Added" input field
    $orderedItems_Sku = $request->get('productSku');
    foreach($orderedItems_Sku as $key => $v)
    {

      $data = [
        'orderId' => $request->get('orderId'),
        'productSku' => $v,
        'orderQty' => $request->get('orderQty') [$key],
        'uomId' => $request->get('uomId'),
        'orderPrice' => $request->get('orderPrice') [$key],
        'orderDiscount' => $request->get('orderDis') [$key],
        'orderPerAmount' => $request->get('orderPerAmount') [$key],
        'created_at' =>  \Carbon\Carbon::now(), # \Datetime()
        'updated_at' => \Carbon\Carbon::now()  # \Datetime()
      ];
      \App\orderedItem::insert($data);
      // "Decrement" means, product quantity will be deducted based on how much quantity that customer has ordered.
      \App\Product::where("productSku", $v)->decrement("productQty", $request->orderQty [$key]);
    }
    \App\Order::insert($orderer);

    $validated = $request->validated();
    return redirect('orders')->with('success', 'Order Successfully Added!'); 
}

这是我在OrderRequest中的代码

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Request;

class OrderRequest 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()
{ 
    $rules = [
        'name' => 'required',
    ];

    foreach($this->request->get('productSku') as $key => $val)
    {
        $product = \App\Product::find($val);
        $rules['orderId'] = 'unique:orders'; 
        $rules['customerId'] = 'required';
        $rules['orderStatusId'] = 'required';
        $rules['paymentMethodId'] = 'required';
        $rules['uomId'] = 'required';
        $rules['productSku.'.$key] = 'required';
        $rules['orderQty.'.$key] = 'required|numeric|min:1|lte:'.$product['productQty'];
        $rules['orderPrice.'.$key] = 'required';
    }
    return $rules;
}

public function messages() 
{
    $messages = [];
      foreach($this->request->get('productSku') as $key => $val)
      {
        $product = \App\Product::find($val);
        $messages['orderQty.'.$key.'.lte'] = 'Quantity of product no. 
'.$product['productSku'].' must be not greater than '.$product['productQty'];
      }
      return $messages;
}
}

如您所见,我已经创建了自己的请求文件(OrderRequest)并从OrderController调用它。

在OrderRequest文件中,我进行了一个foreach循环,以确保验证可在我的动态字段(包括lte / gte规则)中使用。

对于自定义消息,我也做了一个foreach循环,因为我想如下所示动态显示错误(请参见图片),

create blade file

感谢所有向我建议各种解决方案的人,以解决此问题。 :D

答案 1 :(得分:0)

尝试这个

'orderQty.*' => 'required|numeric|min:1|max:'.$product['productQty'] 

答案 2 :(得分:-1)

您可以创建自己的请求:

php artisan make:request {请求名称}

然后,您可以按照这些文档中显示的默认请求相同的方式使用此请求

https://laravel.com/docs/5.7/requests

如果您添加另一种称为“消息”的方法,则可以添加如下消息:

public function messages() {
    return [
        '{variable name}.{validation method}' => '{message to user}'
    ]
}

然后您将收到一个包含错误消息的ajax响应。

希望有帮助

更新

上述建议是最佳做法,因为您正在通过空白的“请求”传递所有数据

更改:

'required|numeric|min:1|lte:'.$product['productQty'],

收件人:

'required|numeric|min:1|lte:productQty',

这告诉验证者orderQty必须小于或等于productQty的输入