Live Chat Icon For mobile
Live Chat Icon

How to add custom validation in Blazor using custom validation attribute?

Platform: Blazor| Category : General, Forms and validation

By default, the System.ComponentModel.Annotations library provides different validation attributes. However, to add a new or custom validation, users can create a custom validation attribute and apply it to their model class. To create an attribute:

  1. Create a Blazor WebAssembly application by referring to this link.

  2. Then, create a new Class Library and name it as Shared to handle custom validation using the custom validation attribute.

    Class library

  3. Now, add the Shared project to the existing Blazor WebAssembly application using the following steps.

       
    •   Right click the Blazor WebAssembly application name and select Add à Project Reference.
    •  
    • In the Reference Manager dialog, select the Shared project as shown. Click OK
    • .
      Reference Manager
       
    •   After the Shared project is added, the Blazor WebAssembly application looks like the following
    .
    Shared Project

  4. Install the System.ComponentModel.Annotations NuGet package to perform custom validation in the Shared project.

  5. In this illustration, two form fields, Name and Organization, are declared inside the model Customer class, and the custom validation attribute for the Organization is set. When the user enters an incorrect Organization name, a validation message appears. In this illustration, the Organization name is set to “Microsoft”, and if the user enters a value other than “Microsoft”, the validation message “Invalid customer log-in.” appears.

  6. In the Shared class library, rename the Class1.cs as Customer.cs and create a model Customer class.

     using System.ComponentModel.DataAnnotations;
     
    namespace Shared
    {
        public class Customer
        {
            [Required]
            public string Name { get; set; }
     
            [Required]
            public string Organization { get; set; }
        }
    }

     

  7. Create a new OrganizationValidationAttribute.cs and then the OrganizationValidationAttribute class, which is derived from ValidationAttribute. The ValidationAttribute from System.ComponentModel.Annotations acts as the base class for validation.
    [OrganizationValidationAttribute.cs]

      using System.ComponentModel.DataAnnotations;
     
    namespace Shared
    {
        public class OrganizationValidationAttribute : ValidationAttribute
        {
            public string ValidOrganizationName { get; set; }
     
            protected override ValidationResult IsValid(object value, ValidationContext validationContext)
            {
                string fieldValue = value.ToString().ToLower();
                if (fieldValue.Equals(ValidOrganizationName.ToLower()))
                    return null;
                return new ValidationResult(ErrorMessage, new[] { validationContext.MemberName });
            }
        }
    }

    The ValidOrganizationName property can be set from the model Customer class. Following that, override the IsValid method, which takes two parameters, value and validationContext. The value parameter contains the value that the user entered in the Organization field. The validationContext parameter is used to explain the context in which validation is performed. If the value is equal to the ValidOrganizationName, no errors will be thrown; otherwise, an error message returns.

      Shared Solution Explorer

  8. Add the following custom validation attribute to the Organization property.

    [Required]
    [OrganizationValidation(ErrorMessage = "Invalid customer log-in.", ValidOrganizationName = "Microsoft")]
    public string Organization { get; set; }

     

  9. Moving back to the Blazor WebAssembly application, add the following code to the Index.razor page to render a form with validation settings.
    [Index.razor]

           @page "/"
     
    <EditForm Model="_product" OnValidSubmit="Submit" style="width:600px;">
        <DataAnnotationsValidator />
        <div class="form-group row">
            <label for="name" class="col-md-2 col-form-label">Name:</label>
            <div class="col-md-10">
                <InputText id="name" class="form-control" @bind-Value="_product.Name" />
                <ValidationMessage For="@(() => _product.Name)" />
            </div>
        </div>
        <div class="form-group row">
            <label for="organization" class="col-md-2 col-form-label">Organization:</label>
            <div class="col-md-10">
                <InputText id="supplier" class="form-control" @bind-Value="_product.Organization" />
                <ValidationMessage For="@(() => _product.Organization)" />
            </div>
        </div>
        <div class="row">
            <div class="col-md-12 text-right">
                <button type="submit" class="btn btn-success">Submit</button>
            </div>
        </div>
    </EditForm>

     

  10. Create a new Index.razor.cs inside the Pages folder and add the following code for Customer class initialization and form submission.
    [Index.razor.cs]

       using Shared;
    using System;
     
    namespace CustomValidationAttributes.Pages
    {
        public partial class Index
        {
            private Customer _product = new Customer();
            public void Submit() =>
                Console.WriteLine($"{_product.Name}, {_product.Organization}");
        }
    }

    The following outputs will be seen after submitting the form.
    Validation Message Output

    Shared Project Output

Share with

Share on twitter
Share on facebook
Share on linkedin

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.