7

我正在尝试使用 Laravel Livewire,我遇到了一种情况,即使表单已成功提交,也会显示以前的错误。

在点击保存之前

发送前

点击保存后

发送后

name刀片文件中的 Html 段customer-new.blade.php

<div class="form-group">
    <div class="border rounded-0 px-1">
        <label class="mb-0" for="name">Name</label>
        <input wire:model="name" type="text" class="form-control form-control-sm " id="customer-name" aria-describedby="customer-nameHelp">
    </div>
    @error('name') <span class="err-message">{{ $message }}</span> @enderror
</div>

保存按钮代码:

<button 
  wire:click="store" 
  wire:loading.attr="disabled" 
  wire:target="store" 
  type="submit" 
  class="btn btn-sm btn-light">Save
</button>

storeCustomerNew.php 的方法:

public function store()
{
    $this->validate([
        'name' => 'required|max:80',
        'street' => 'required|max:100',
        'city' => 'required|max:40',
        'dueAmount' => 'numeric|min:0'
    ]);

    Customer::create([
        'name' => $this->name,
        'street' => $this->street,
        'city' => $this->city,
        'due_amount' => $this->dueAmount,
    ]);

    session()->flash('message', 'Customer was saved');

    $this->clear();
}

clear()方法如下:

public function clear() {
  $this - > name = '';
  $this - > street = '';
  $this - > city = '';
  $this - > dueAmount = 0;
}
4

3 回答 3

19

根据文档https://laravel-livewire.com/docs/input-validation

您需要随时重置验证

直接错误消息操作 validate() 和 validateOnly() 方法应该可以处理大多数情况,但有时您可能希望直接控制 Livewire 的内部 ErrorBag。

Livewire 为您提供了一些方法来直接操作 ErrorBag。

从 Livewire 组件类中的任何位置,您都可以调用以下方法:

    $this->addError('email', 'The email field is invalid.');
    // Quickly add a validation message to the error bag.
    
    $this->resetErrorBag();
    $this->resetValidation();
    // These two methods do the same thing. The clear the error bag.
    // If you only want to clear errors for one key, you can use:
    $this->resetValidation('email');
    $this->resetErrorBag('email');
    
    $errors = $this->getErrorBag();
    // This will give you full access to the error bag,
    // allowing you to do things like this:
    $errors->add('some-key', 'Some message');

暗示

我在水合物功能上使用重置方法,如下所示

...
    public function hydrate()
    {
        $this->resetErrorBag();
        $this->resetValidation();
    }
...
于 2020-06-15T02:37:14.200 回答
1

您应该使用 livewire 的reset方法重置公共属性。删除您的$this->clear()方法定义并将其替换为以下内容:

$this->reset('name', 'street', 'city', 'dueAmount');
于 2020-03-23T19:12:58.393 回答
0

将 id 添加到错误消息 div

@error('name') <span class="err-message" id="name-error">{{ $message }}</span> @enderror

@error('street') <span class="err-message" id="street-error">{{ $message }}</span> @enderror

@error('city') <span class="err-message" id="city-error">{{ $message }}</span> @enderror

@error('due_amount') <span class="err-message" id="due_amount-error">{{ $message }}</span> @enderror
于 2020-09-25T09:45:22.290 回答