Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blazor Change Validation default CSS class names

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

like image 854
Engr Rslan Avatar asked Oct 02 '19 10:10

Engr Rslan


3 Answers

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";
    }
}
like image 145
user774031 Avatar answered Oct 19 '22 09:10

user774031


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

like image 39
Samer Awajan Avatar answered Oct 19 '22 08:10

Samer Awajan


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.

like image 2
bjorn-consid Avatar answered Oct 19 '22 09:10

bjorn-consid