Search code examples
laravel-livewire

Laravel 10 Livewire 3 - "validation" attribute doesn't work


I want to use the "#[Validate]" attribute to validate a form post. When I run it I receive the error:

  Missing [$rules/rules()] property/method on Livewire component: [contactform].

...seems to be ignoring the validation attribute entirely:

namespace App\Livewire;

use Livewire\Component;
use Livewire\Attributes\Validate;

class Kontaktform extends Component
{

    #[Validate('required',message: 'Please provide your name')]
    #[Validate('max:255')]
    public $name = '';

.
.
.
   
   //Validate and submit
    public function submitForm(){
    $validated = $this->validate();  <-----error points to this line :S
    dd($validated);

   }
.
.
.

Solution

  • Replace:

       #[Validate('required',message: 'Please provide your name')]
        #[Validate('max:255')]
        public $name = '';
    

    With:

    #[Validate]
    public $name = '';
    

    And add the following 2 methods in your livewire component:

          public function rules()
          {
            'name' => 'required|max:255'
          }
    
      public function messages()
      {
        return [
          'name.required' => 'Please provide your name',
          'name.max:255' => 'Name cannot exceed 255 characters'
        ];
      }