Search code examples
laraveltailwind-csslaravel-livewire

Custom validation on radio buttons if not selected | Tailwind


How to validate by showing a red ring around the radio button and make text red. Currently I am just showing a validation popup message. See image for a better idea.

Radio component

<input type="radio" {!! $attributes->class(['border-gray-300 text-gray-600 shadow-sm focus:border-gray-300 focus:ring focus:ring-gray-200 focus:ring-opacity-50', 'border-red-500 text-red-500' => $errors->has($attributes->get('name'))]) !!} />

Livewire view snippet

  <div class="space-y-5">
  @foreach ($ticket_types as $ticket_type)
  <div>
    <div class="relative flex items-start">
      <div class="absolute flex items-center h-5">
        <x-radio-button wire:model="ticket_type" @click="isQuestion = false" id="{{ $ticket_type->id }}" aria-describedby="{{ $ticket_type->id }}_description" value="{{ $ticket_type->id }}" class="h-4 w-4 transition duration-150 ease-in-out" />
      </div>
      <div class="pl-7 text-sm leading-5">
        <x-jet-label for="{{ $ticket_type->id }}_title">
          {{ $ticket_type->title }}
        </x-jet-label>
        <p id="{{ $ticket_type->id }}_description" class="text-gray-500">
          {{ $ticket_type->description }}
        </p>
      </div>
    </div>
  </div>
  @endforeach
</div>
<x-input-error for="ticket_type" />

Current look and feel

enter image description here

What I want to achieve (ignore the checkbox part)

enter image description here


Solution

  • You can conditionally include classes on components. So you could do something like:

    <input type="radio" 
      {!! $attributes->class([
    
        // these styles are applied by default
        'border-gray-300 text-gray-600 shadow-sm focus:border-gray-300 focus:ring focus:ring-gray-200 focus:ring-opacity-50',
    
        // these are applied if the name of the component is found in the error bag
        // meaning there was an error
        'border-red-500 text-red-500' => $errors->has($attributes->get('name'))
        ]) 
    
      !!} />