I'm trying out Blazor right now, with my choice of CSS framework being Tailwind.
Now, getting Tailwind built and integrated is easy enough, but I am struggling to find a resource on how to conditionally apply classes depending on an input validation state. Blazor itself adds an invalid class, but that obviously does not work with the styling approach Tailwind uses.
Basically I have this code:
<div class="mt-1">
<InputText @bind-Value="LoginRequest.UserName" id="userName" type="text" required
class="appearance-none block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"/>
<ValidationMessage For="@(() => LoginRequest.UserName)"/>
</div>
... and want to conditionally change, for example border-gray-300 to border-red-300 if the field validation failed.
Is this possible? If yes, I would love some pointers.
Cheers
This seems to be possible with the new .NET 5 release:
<EditForm EditContext="@_loginContext">
... body ...
</EditForm>
@code{
static UserLoginRequest LoginRequest { get; set; } = new();
readonly EditContext _loginContext = new(LoginRequest);
protected override void OnInitialized()
{
base.OnInitialized();
_loginContext.SetFieldCssClassProvider(new TailwindClassProvider());
}
private class TailwindClassProvider : FieldCssClassProvider
{
public override string GetFieldCssClass(EditContext editContext, in FieldIdentifier fieldIdentifier)
{
var isValid = !editContext.GetValidationMessages(fieldIdentifier).Any();
return isValid ? "border-gray-300 placeholder-gray-400 focus:ring-indigo-500 focus:border-indigo-500" : "border-red-300 text-red-900 placeholder-red-300 focus:ring-red-500 focus:border-red-500";
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With