Skip to content

Custom validation attribute with DI #26457

@guardrex

Description

@guardrex

For the Custom validation attributes section and per PU work on dotnet/aspnetcore#39445, we can demo an example along the lines of the basic test app, which is ...

Pages/ValidationWithDI.razor:

@page "/validation-with-di"
@using System.ComponentModel.DataAnnotations
@using Microsoft.AspNetCore.Components.Forms

<EditForm Model="@this" autocomplete="off">
    <DataAnnotationsValidator />

    <p class="the-quiz">
        Name something you can put in a salad:
        <input @bind="SaladIngredient" 
            class="@context.FieldCssClass(() => SaladIngredient)" />
    </p>

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

    <ul class="validation-errors">
        @foreach (var message in context.GetValidationMessages())
        {
            <li class="validation-message">@message</li>
        }
    </ul>

</EditForm>

@code {
    [SaladChefValidator]
    public string SaladIngredient { get; set; }

    public class SaladChefValidatorAttribute : ValidationAttribute
    {
        protected override ValidationResult IsValid(object value, 
            ValidationContext validationContext)
        {
            var saladChef = validationContext.GetRequiredService<SaladChef>();

            if (saladChef.ThingsYouCanPutInASalad.Contains(value.ToString()))
            {
                return ValidationResult.Success;    
            }

            return new ValidationResult("You should not put that in a salad!");
        }
    }

    // Simple class to check if DI can be used in Validation attributes
    public class SaladChef
    {
        public string[] ThingsYouCanPutInASalad = { "Strawberries", "Pineapple", 
            "Honeydew", "Watermelon", "Grapes" };
    }
}

... and assuming the BlazorSample namespace ...

builder.Services.AddTransient<BlazorSample.ValidationWithDI.SaladChef>();

Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

Metadata

Metadata

Assignees

Type

No type
No fields configured for issues without a type.

Projects

Status

Done

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions