Lucas
Lucas

Reputation: 83

Blazor Server Custom ValidationAttribute using Database

I'm trying to implement a custom validation attribute for unique records. For that I need to check the database, so I can notify user that given data already exists.

For that I need to access database inside of IsValid method of my Custom validation attribue:

public class CustomValidationAttribute : ValidationAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            //This is always null
            var context = (DataContext)validationContext.GetService(typeof(DataContext));
            
        }
    }

I alredy tried to implement custom DataAnotation with DI acording to this post: stack overflow link

but it does not work. Maybe due to .net6 changes? I get error that EditContext cannot by changed dynamicaly.

Can some point me in the rigth direction please? Thank you.

Upvotes: 0

Views: 510

Answers (1)

Eugen Spinne
Eugen Spinne

Reputation: 83

Dependency Injection in ValidationAttributes should be available with .net7.0-preview1: https://github.com/dotnet/aspnetcore/pull/39445

Upvotes: 1

Related Questions