I'm trying Microsoft Blazor and when working with forms and validation I stopped on how can I change the default CSS class that will be added by default on InputText
Validation State.
For Explanation when InputText
has an error by default take class "invalid
" I want to change this class to "is-invalid
"
I need best practices.
Thanks, StackOverflow community
This is now customizable, see here: https://learn.microsoft.com/en-us/aspnet/core/blazor/forms-validation?view=aspnetcore-5.0#custom-validation-class-attributes
var editContext = new EditContext(model);
editContext.SetFieldCssClassProvider(new MyFieldClassProvider());
...
private class MyFieldClassProvider : FieldCssClassProvider
{
public override string GetFieldCssClass(EditContext editContext,
in FieldIdentifier fieldIdentifier)
{
var isValid = !editContext.GetValidationMessages(fieldIdentifier).Any();
return isValid ? "good field" : "bad field";
}
}
Any HTML element (or InputText) attribute including the class, can be 'one-way' bound to a variable or expression. So in your case, you could do:
<input type="text" class="@((any_validation_condition)? "error_css_class" : "")" />
or just bind to a variable and set that variable at run-time to reflect the suitable display class of the element.
Thanks
Yes true it's customizable in Core 5.0, but the examples given is not working as is. The method HandleSubmit
must take EditContext
as argument, and the custom FieldCssClassProvider
be set there, not in OnInitialized()
as in the examples.
private async Task HandleSubmit(EditContext context)
{
context.SetFieldCssClassProvider(new MyFieldClassProvider());
var isValid = context.Validate();
if (isValid)
{
//...
}
else
{
//...
}
My MyFieldClassProvider()
returns "is-valid
" and "is-invalid
" and this works with Bootstrap.
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