To add custom CSS class names to input components despite bootstrap and other CSS framework styling, follow the steps below.
In the wwroot/css/site.css stylesheet, include the following styles.
.validField {
outline: 2px dotted green;
}
.invalidField {
outline: 2px dotted red;
}Create a new Customer.cs and model Customer class.
using System.ComponentModel.DataAnnotations;
namespace CustomCSS_Validation_InputComponent
{
public class Customer
{
[Required]
public string Name { get; set; }
[Required]
[StringLength(4, ErrorMessage = "The organization code must be less than 5 characters in length.")]
public string OrganizationCode { get; set; }
}
}Create a new CustomFieldCssClassProvider.cs and then the CustomFieldCssClassProvider class.Inherit the CustomFieldCssClassProvider class from FieldCssClassProvider and override the GetFieldCssClass method, which helps to check for validation messages with the EditContext and returns the “validField” or “invalidField” class name to the appropriate field.
using Microsoft.AspNetCore.Components.Forms;
using System.Linq;
namespace FormBootstrapCSS.Data
{
public class CustomFieldCssClassProvider : FieldCssClassProvider
{
public override string GetFieldCssClass(EditContext editContext,
in FieldIdentifier fieldIdentifier)
{
var isValid = !editContext.GetValidationMessages(fieldIdentifier).Any();
return isValid ? "validField" : "invalidField";
}
}
}
Add the form design code as well as the code for input components validation to the Index.razor page. Here, the SetFieldCssClassProvider method in the EditContext class is used to set the custom CSS name to the appropriate field based on the validation result returned by the CustomFieldCssClassProvider class, whose instance is passed into the method.
@page "/"
<EditForm EditContext="@editContext" OnValidSubmit="@Submit">
<DataAnnotationsValidator />
<ValidationSummary />
<div class="mt-2 col-md-12">
Name: <InputText id="name" @bind-Value="_customer.Name" />
</div>
<div class="mt-2 col-md-12">
Organization Code: <InputText id="organizationCode" @bind-Value="_customer.OrganizationCode" />
</div>
<div class="mt-2 col-md-12">
<button type="submit">Submit</button>
</div>
</EditForm>
@code {
private Customer _customer = new Customer();
private EditContext editContext;
protected override void OnInitialized()
{
editContext = new(_customer);
editContext.SetFieldCssClassProvider(new CustomFieldCssClassProvider());
}
private void Submit()
{
…….. . .
}
}
View Sample in GitHub
Share with