Livewire: Declare form validation rules once

Created on 18 Mar 2020  路  3Comments  路  Source: livewire/livewire

I would like to declare form validation rules only once
This does not work.

protected $rules;

    public function mounted() {

        $this->rules = [
            'first_name' => 'required|between:3,50',
            'last_name' => 'required|between:3,75',
            'type' => [
                      'required', 
                      Rule::in(['COMPANY', 'PRIVATE'])
            ],
            'company' => 'nullable|between:3,70',
            'email' => 'required|email:rfc,dns,spoof|unique:leads',
            'phone' => 'required|phone_number',
            'message' => 'required|between:10,70',
        ];
    }

    public function updated($field)
    {
        $this->validateOnly($field, $this->rules);
    }

    public function submit()
    {
        $validatedData = $this->validate($this->rules);
    }

(Yes I am a sponsor)

All 3 comments

Make a method called "->getRules()" that returns that rules array and use it where you need to.

And thanks for sponsoring!

Also, that doesn't work because protected properties are not persisted between requests.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

cao-minh-duc picture cao-minh-duc  路  4Comments

roni-estein picture roni-estein  路  3Comments

zaherg picture zaherg  路  4Comments

mokhosh picture mokhosh  路  3Comments

mokhosh picture mokhosh  路  4Comments