3
votes

Before I applied new livewire V2 programming style I had a form that was wired to a Model's individual properties. To trigger the real time validation for fields, I used this in the component (e.g. name property):

public function updatedName(){
      $this->validate(['name' =>'required|max:127']);
}

name being a property of a Model named Malt. My question is: how to modify this updatedName() function ?

I already understood that I should rename the function to updatedMaltName, thus I tried this.

public function updatedMaltName(){ 
  $this->validate(['name' =>'required|max:127']);
}

but it doesn't work. Instead it display an error "The name field is required" as soon as I type a char in the field (which is the opposite of what should happen), and never hide this error even if I empty the field.

I also tried this

public function updatedMaltName(){
      $this->validate(['malt.name' =>'required|max:127']);
    }

but this doesn't work at all.

1

1 Answers

7
votes

Define your ruleset in a $rules property in your component-class.

protected $rules = [
    'malt.name' => 'required|max:127',
];

You can now hook into the updated() method and validateOnly() on the field that was just now updated. This will now validate any fields being updated on your model, with the rulset defined in $rules.

public function updated($property)
{
    $this->validateOnly($property);
}

The $property argument is the name of the field you are updating, so for example malt.name.

You can of course hook into the specific property you are updating, and validate only that field. This assumes you have a model in a property $malt that has a property name in it.

public function updatedMaltName()
{
    $this->validateOnly('malt.name');
}