How do I create and use a custom validation component?

Platform: Blazor| Category : Forms and validation, General

To create a custom validation component in Blazor, follow these code steps:

  1. Create a Blazor Server or WebAssembly application and install the System.ComponentModel.Annotations NuGet package using NuGet Package Manager.

  2. Now, create a new custom validation class in the Pages folder and restrict the user to enter only “admin” in the password field.
    [CustomValidatorAttribute.cs]

    using System.ComponentModel.DataAnnotations;
     
    namespace {{Your_App_Name}}.Pages
    {
    public class CustomValidationAttribute : ValidationAttribute
    {
    public string? ValidUserName { get; set; }
    protected override ValidationResult? IsValid ( object? username, ValidationContext validationContext )
    {
    var content = username?.ToString()?.ToLower();
    if (content!.Equals(ValidUserName?.ToLower()))
    {
    return null;
    }
    return new ValidationResult(ErrorMessage, new[] { validationContext.MemberName });
    }
    }
    }
  3. Use the created custom validator attribute in the Razor component. Provide the error message and valid username properties for validation.
    [Index.razor]

    @page "/"
    @using System.ComponentModel.DataAnnotations
     
    <EditForm style="width:470px;" Model="_login" OnValidSubmit="Submit">
        <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="_login.UserName" />
                <ValidationMessage For="@(() => _login.UserName)" />
            </div>
        </div>
     
        <div class="form-group row">
            <label for="supplier" class="col-md-2 col-form-label">Password:</label>
            <div class="col-md-10">
                <InputText id="supplier" class="form-control" @bind-Value="_login.Password" />
                <ValidationMessage For="@(() => _login.Password)" />
            </div>
        </div>
     
        <div class="row">
            <div class="col-md-12 text-right">
                <button type="submit" class="btn btn-success">Submit</button>
            </div>
        </div>
    </EditForm>
     
    @code {
        private Login _login = new Login();
     
        public void Submit()
        {
            Console.WriteLine($"User name is {_login.UserName} and password is {_login.Password}");
        }
     
        public class Login
        {
            [Required]
            [CustomValidation(ErrorMessage = "The entered username is wrong ", ValidUserName = "admin")]
            public string? UserName { get; set; }
            [Required]
            public string? Password { get; set; }
        }
    }

     

  4. Refer to the following output image for the custom validator.

    Refer to this link for more details.


    View Sample in GitHub

Share with

Related FAQs

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

Please submit your question and answer.