Adding classes to Blazor(Razor) Validation

Viewed 2941

I know things are still pretty early in the Blazor development track, but I'm wondering if anyone has come across a way to apply classes to a Blazor (Razor) validation message? Here's a sample of code.

        <EditForm Model="@Employee" OnValidSubmit="@HandleValidSubmit">
        <DataAnnotationsValidator />
        <ValidationSummary />
        <div class="form-group row">
            <label for="lastName" class="col-sm-3">Last Name: </label>
            <div class="col-sm-8">
                <InputText id="lastName" @bind-Value="@Employee.LastName" class="form-control" placeholder="Enter last name" />
                <ValidationMessage For="@(() => Employee.LastName)" />
            </div>
        </div>

I'd like to be able to add a text-danger, col-sm-8 or other classes to the validation message. I already know that I could do it with CSS using the default validation-error class.

2 Answers

As suggested above, you can subclass the ValidationMessage component class... I'll give you a simpler solution, since I prefer not to have a myriad of classes on my projects just for changing the appearance a little.

Just wrap the ValidatorMessage with a div and apply classes to it:

<div class="col-sm-8 text-danger">
    <ValidationMessage For="@(() => Employee.LastName)" />
</div>

Anyway, what the ValidationMessage component does (by code) is rendering a simple div with the class "validation-message" so, if you have problems with any style not being applied, take into account that you can force styles using the right CSS selectors (and maybe some !important tags...).

It seems like you can't add a class, but you can add styles:

<ValidationMessage
    For="..."
    style="color: #dc3545!important;
           flex: 0 0 66.666667%;
           max-width: 66.666667%;" />

You can also override the validation-message class as documented here.

Related