Laravel Livewire 错误未清除

Lak*_*tne 6 laravel-validation laravel-livewire

我正在试验 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>
Run Code Online (Sandbox Code Playgroud)

和保存按钮代码:

<button 
  wire:click="store" 
  wire:loading.attr="disabled" 
  wire:target="store" 
  type="submit" 
  class="btn btn-sm btn-light">Save
</button>
Run Code Online (Sandbox Code Playgroud)

store CustomerNew.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();
}
Run Code Online (Sandbox Code Playgroud)

和clear()方法是这样的:

public function clear() {
  $this - > name = '';
  $this - > street = '';
  $this - > city = '';
  $this - > dueAmount = 0;
}
Run Code Online (Sandbox Code Playgroud)

amr*_*phy 15

根据文档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');
Run Code Online (Sandbox Code Playgroud)

暗示

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

...
    public function hydrate()
    {
        $this->resetErrorBag();
        $this->resetValidation();
    }
...
Run Code Online (Sandbox Code Playgroud)

  • 我想调用 `$this-&gt;resetValidation()` 就足够了,因为它在内部调用了 `resetErrorBag()` 方法 (3认同)

小智 0

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

$this->reset('name', 'street', 'city', 'dueAmount');
Run Code Online (Sandbox Code Playgroud)