Override Validation Classes in Blazor App Using EditContext

In this blog post, I will show you how to override the CSS in EditContext. For example, assume you already have the CSS classes for the error message. Then, when the blazor adds the validation error message, you want to override the class. You can do this very easily with the blazor app.
The blazor framework provides a class  FieldCssClassProvider you can use to override the default CSS class that blazor applies to input control when a validation error occurs.


Supplies CSS class names for form fields representing their validation state or other state information from an EditContext.

Let’s create a simple demo to understand this; as shown in the image below, I have added two custom classes, one for error and one for success.

To override the CSS, follow these steps.

  • Create a model class and add the required DataAnotation; as you can see, I have added Required and Range

  public class ExampleModel
    [StringLength(10, ErrorMessage = "Name is too long.")]
    public string? Name { get; set; }
    public int Age {get;set;}
  • In the edit form, replace Model with the private instance of EditContext.


       border: 5px solid #ffdddd;
       border:  5px  solid  green;

<EditForm EditContext="_editContext" OnValidSubmit="@HandleValidSubmit">
    <DataAnnotationsValidator />

        <InputText id="name" @bind-Value="exampleModel.Name" />
    <ValidationMessage For="() => exampleModel.Name" />

         <InputNumber id="age" @bind-Value="exampleModel.Age" />

    <ValidationMessage For="() => exampleModel.Age" />

    <button type="submit">Submit</button>

@code {
    private ExampleModel exampleModel = new();
    private string message="";
    private EditContext _editContext;
    protected override void OnInitialized(){

	_editContext=new EditContext(exampleModel);
	_editContext.SetFieldCssClassProvider(new CustomCssProvider());
    private void HandleValidSubmit()
        message="HandleValidSubmit called";

        // Process the valid form
  • Create a CustomCssProvider class; you can name it anything and inherits it from the FieldCssClassProvider class and return the CSS classes that you want to use
  • After that,  set the _editContext.SetFieldCssClassProvider(new CustomCssProvider());


 public class CustomCssProvider:FieldCssClassProvider
public override string GetFieldCssClass(EditContext editContext,in FieldIdentifier fieldIdentifier){
	var isValid=!editContext.GetValidationMessages(fieldIdentifier).Any();
		return isValid? "custom-success" : "custom-error";
		return isValid ? "": "custom-error";


@code {


CustomCss Class Demo

Post a Comment

Please do not post any spam link in the comment box😊

Previous Post Next Post

Blog ads