SuperJMN
SuperJMN

Reputation: 13992

Avoiding duplication in FluentValidations

I have a validator for a CreateRequest and another for UpdateRequest.

I soon discovered that they are the same. The only difference is that one has an Id (UpdateRequest).

The validations are the same, to the same properties, but the entities are different.

How can I avoid duplicating the rules?

Currently I have

public class CreateValidator : AbstractValidator<CreateRequest> 
{
     RuleFor(p => p.Prop1)...  // Rule 1
     RuleFor(p => p.Prop2)...  // Rule 2
     RuleFor(p => p.Prop3)...  // Rule 3
}

public class UpdateValidator : AbstractValidator<UpdateRequest> 
{
     RuleFor(p => p.Id)...     // Rule 0
     RuleFor(p => p.Prop1)...  // Rule 1
     RuleFor(p => p.Prop2)...  // Rule 2
     RuleFor(p => p.Prop3)...  // Rule 3
}

They are the same except for the Rule 0.

Can I avoid duplication?

Upvotes: 0

Views: 327

Answers (1)

Roman Koliada
Roman Koliada

Reputation: 5112

  1. Make sure that your CreateRequest and UpdateRequest implement the same interface of are inherited from some base class(or one from another).

    public CreateRequest: Request{...}
    public UpdateRequest: Request{...}
    
  2. Create a generic validator class with restricted generic type parameter.

    public RequestValidator: AbstractValidator<T> where T: Request
    {
        RequestValidator()
        {
             RuleFor(p => p.Prop1)...  // Rule 1
             RuleFor(p => p.Prop2)...  // Rule 2
             RuleFor(p => p.Prop3)...  // Rule 3
        }
    }
    
  3. Create actual validator using inheritance.

    public CreateRequestValidator: RequestValidator<CreteRequest>
    {
        CreateRequestValidator()
        { }
    }
    public UpdateRequestValidator: RequestValidator<UpdateRequest>
    {
        UpdateRequestValidator()
        {
             RuleFor(p => p.Id)...           
        }
    }
    

Upvotes: 1

Related Questions