Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

graeme14's avatar

livewire validation with highlighted input fields

So I was playing about with Livewire, and having a go at validations. While experimenting, I learned how to display error messages and submit the form successfully. However, when I tried changing the border colours to correspond with the errors, the form crashed and would not reset

Here's what I tried to do:

Name @error('name')

{{ $message }}

@enderror

And here's how I got it to work:

Name @error('name')

{{ $message }}

@enderror

That's probably not the best method (slightly adapted from a 6+ year old stack overflow thread), but it's the best I've got and it works.

Can anyone explain to me why I can't simply use @error('...') @enderror to change the border colours?

0 likes
2 replies
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

To change the border color of an input field based on validation errors, you can use the class directive in Livewire. Here's an example:

<div>
    <label for="name">Name:</label>
    <input type="text" id="name" wire:model="name" 
        class="@error('name') border-red-500 @enderror">
    @error('name')
        <p class="text-red-500">{{ $message }}</p>
    @enderror
</div>

In this example, we're using the class directive to conditionally add the border-red-500 class to the input field when there's a validation error on the name field. This will add a red border to the input field. We're also using the @error directive to display the validation error message below the input field.

Note that we're using the text-red-500 class to style the error message. You can adjust the classes to match your preferred styling.

I hope this helps!

1 like
xalafnasirov's avatar

There are pretty much few options but if you want to work alongside back-end validation and front-end result. I can suggest you this (Design perspective depend on yours, it is mine)

  1. First create style (css)
.success-input-style {
  border: 2px solid #28a745;
}

.error-input-style {
  border: 2px solid #F02801;
}
  1. Create input
<input  wire:model.live='input' type="text" 
   @class([
     'error-input-style'=>$errors->has('input'),
     'success-input-style' => !$errors->has('input') && $input,
]) placeholder="your input">                		
  1. Last step create vaidation in livewire and done
public $input;

protected $rules = [
    'input' => 'required|string|max:255',
];

public function updatedInput() {
    $this->validateOnly('input');
}

Now this will work like water flows on river. Good luck!!!

2 likes

Please or to participate in this conversation.