I've one form input
field where I want to add some classes to make the border of the input
box as red color when I'll get some validation error in the html form. How can I do this?
Currently, I'm using the following code to show the validation error message which is working fine. But, with this I also want to make the border of input
filed as red color to highlight that.
<div>
<label for="email" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Name</label>
<input type="text" name="name" id="name"
class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" placeholder="Write your name" />
{
action.value?.failed && <p class="mt-2 text-sm text-red-600 dark:text-red-500">{action.value.fieldErrors?.name}</p>
}
</div>
It'll be like by default, that border-gray-300
class must be in the template. But, whenever I'll get a validation error I want to update that by border-red-300
---Updated Working Code---
The updated sample code is like this. I don't know how much it's neat & optimize. But it's working now. Thanks to "Giorgio Boa". Job done. :D
<div>
<label for="email" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Name</label>
<input type="text" name="name" id="name"
class={['bg-gray-50 border text-gray-900 sm:text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500', (action.value?.failed && action.value.fieldErrors?.name) ? 'border-red-300' : 'border-gray-300']} placeholder="Write your name" />
{
action.value?.failed && <p class="mt-2 text-sm text-red-600 dark:text-red-500">{action.value.fieldErrors?.name}</p>
}
</div>
Here is the documentation
e.g. This will apply the border-red-300 class to the button when isError is true, and remove it when it's false. You can use conditional classes with this syntax
<button class={`your_classes ${isError.value ? 'border-red-300' : ''}`}>
Click me
</button>
or in this way
<button class={{ 'your_classes' : true, 'border-red-300': isError.value }}>
Click me
</button>
or
<button
class={[
'your_classes',
isError.value ? 'border-red-300' : '',
// you can use this alternative syntax
{ 'border-red-300': isError.value },
]}
>
Click me
</button>