Search code examples
laravelvalidation

Laravel livewire realtime validation when required field loses focus


The realtime form validation is working using livewire's out of the box validation feature. But I would like it to work when a required field loses focus and the user doesn't populate the field. Using the rules scoped below, I'm finding that the validation will only work when a space or too few chars are entered into the field. In summary, the 'required' rule doesn't work as I'd expect. I need to tab over the field or click into and out of it without adding anything and then see a 'required data' error when the field loses focus.

Is there a simple fix that I'm missing?

Template

  <input 
           type="text" wire:model.blur="card_name" id="card_name" name="card_name" autocomplete="" required
           class="block w-full rounded-md shadow-sm border-gray-30 focus:ring-governor-bay-500 focus:border-governor-bay-500 sm:text-sm 
@error('card_name') border-red-600 @else border-gray-300 @enderror"               
         >

Component validation

#[Rule([
    'card_name' => 'required|min:5',
], message: [
    'required' => 'Name on card is required.',
    'min' => 'Name on card is too short.',
], attribute: [
    'Name on cards.*' => 'Name on card',
])]
public $card_name = [];

Solution

  • To achieve the behavior you want, you can use JavaScript to handle the input field's focus and blur events, and then explicitly trigger the validation when the field loses focus without any value being entered.

    You can listen for focus and blur events in your livewire component and use custom logic to validate. You can also add your custom errors using.

    $this->addError('Your-field-name', 'custom error message');