Validation In Blazor Application

As we all know validation is very important in any application, its prevent user to submit undesired and inaccurate data. In blazor, we can perform validation using DataAnnotations, this will work with model class property. All validation falls down under “System.ComponentModel.DataAnnotations” namespace. Almost all attributes are the same as ASP.NET MVC which we already use somewhere in the past.

If you are new to Blazor I recommend you should read this article first or if you are looking to perform CRUD operation to perform validation you can read this article. I’m using Blazor_CRUD_Template to perform validation.

Normally in ASP.NET MVC we put required or string length validation as below. This will same in Blazor.

public class Article
   {
       public int ID { get; set; }
       [Required]
       [StringLength(20, ErrorMessage = "A title should not be more than 20 characters.")]
       public string Title { get; set; }
   }

These above attributes will check the required validation and string length validation on the Title filed. In the “StringLength” validation error message is optional and 20 is the max length of the title.

All previous built-in validation attributes are almost identical in blazor.

  • Required
  • StringLength
  • EmailAddress
  • Url
  • Remote
  • RegularExpression
  • Range
  • Phone
  • CreditCard
  • Compare
  • [DataType(DataType.Date)]
  • [DataType(DataType.CreditCard)]
  • [DataType(DataType.CreditCard)]
  • [DataType(DataType.Currency)]
  • [DataType(DataType.Password)]
  • [DataType(DataType.PostalCode)]
  • [DataType(DataType.Upload)]
  • [DataType(DataType.Custom)]

This all validation will work under “EditForm” or you can say “Microsoft.AspNetCore.Components.Forms.EditForm” component, To use calidation we need “DataAnnotationsValidator” compoment  which helps to validate our model. We can pass out model class name in Model attribyte and submit method name we need to pass in OnValidSubmit attribue. we can display all error message together with help of ValidationSummary.

Let’s validate the title filed as required and make only 20 characters to allow.

The Model class will be the same as above.

AddArticle.razor page will change as below.

@page "/addArticle"
@inject IArticleManager articleManager
@inject Microsoft.AspNetCore.Components.NavigationManager navigationManager

<h1>
    Add Article
</h1>

<div class="row">
    <div class="col-md-4">
        <Microsoft.AspNetCore.Components.Forms.EditForm Model="@article" OnValidSubmit="CreateArticle">
            <DataAnnotationsValidator />
            <ValidationSummary />
            <div class="form-group">
                <label for="Name" class="control-label">Name</label>
                <input for="Name" class="form-control" @bind-value="@article.Title" />
            </div>
            <div class="form-group">
                <button type="submit" class="btn btn-primary">Save</button>
                <button type="button" class="btn btn-danger" @onclick="() => cancel()">Cancel</button>
            </div>
        </Microsoft.AspNetCore.Components.Forms.EditForm>
    </div>
</div>

@code {

    Article article = new Article();

    protected async Task CreateArticle()
    {
        await articleManager.Create(article);
        navigationManager.NavigateTo("/articlelist");
    }

    void cancel()
    {
        navigationManager.NavigateTo("/articlelist");
    }
}

We also can display a validation message for each control with the help of “ValidationMessage”.

@page "/addArticle"
@inject IArticleManager articleManager
@inject Microsoft.AspNetCore.Components.NavigationManager navigationManager

<h1>
    Add Article
</h1>

<div class="row">
    <div class="col-md-4">
        <Microsoft.AspNetCore.Components.Forms.EditForm Model="@article" OnValidSubmit="CreateArticle">
            <DataAnnotationsValidator />
            <div class="form-group">
                <label for="Name" class="control-label">Name</label>
                <input for="Name" class="form-control" @bind-value="@article.Title" />
                <ValidationMessage For="@(() => article.Title)" />
            </div>
            <div class="form-group">
                <button type="submit" class="btn btn-primary">Save</button>
                <button type="button" class="btn btn-danger" @onclick="() => cancel()">Cancel</button>
            </div>
        </Microsoft.AspNetCore.Components.Forms.EditForm>
    </div>
</div>

@code {

    Article article = new Article();

    protected async Task CreateArticle()
    {
        await articleManager.Create(article);
        navigationManager.NavigateTo("/articlelist");
    }

    void cancel()
    {
        navigationManager.NavigateTo("/articlelist");
    }
}

 

Recommend articles which you should read once.

  1. CRUD Using Blazor, Entity Framework Core And Dapper
  2. Sorting Table In Blazor
  3. Pagination In Blazor
  4. Searching Feature In Blazor

hope you guys found something useful. Please give your valuable feedback/comments/questions about this article. Please let me know how you like and understand this article and how I could improve it.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories