Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fluent Validations. Inherit validation classes

Tags:

I used Fluent Validator. But sometimes I need create a hierarchy of rules. For example:

[Validator(typeof(UserValidation))] public class UserViewModel {     public string FirstName;     public string LastName; }  public class UserValidation : AbstractValidator<UserViewModel> {     public UserValidation()     {         this.RuleFor(x => x.FirstName).NotNull();         this.RuleFor(x => x.FirstName).NotEmpty();          this.RuleFor(x => x.LastName).NotNull();         this.RuleFor(x => x.LastName).NotEmpty();     } }  public class RootViewModel : UserViewModel {     public string MiddleName;        } 

I want to inherit validation rules from UserValidation to RootValidation. But this code didn't work:

public class RootViewModelValidation:UserValidation<RootViewModel> {     public RootViewModelValidation()     {         this.RuleFor(x => x.MiddleName).NotNull();         this.RuleFor(x => x.MiddleName).NotEmpty();     } } 

How can I inherit validation class using FluentValidation?

like image 265
Ivan Korytin Avatar asked Jan 20 '11 11:01

Ivan Korytin


1 Answers

To resolve this, you must change UserValidation class to generic. See code below.

public class UserValidation<T> : AbstractValidator<T> where T : UserViewModel {     public UserValidation()     {         this.RuleFor(x => x.FirstName).NotNull();         this.RuleFor(x => x.FirstName).NotEmpty();          this.RuleFor(x => x.LastName).NotNull();         this.RuleFor(x => x.LastName).NotEmpty();     } }  [Validator(typeof(UserValidation<UserViewModel>))] public class UserViewModel {     public string FirstName;     public string LastName; }  public class RootViewModelValidation : UserValidation<RootViewModel> {     public RootViewModelValidation()     {         this.RuleFor(x => x.MiddleName).NotNull();         this.RuleFor(x => x.MiddleName).NotEmpty();     } }  [Validator(typeof(RootViewModelValidation))] public class RootViewModel : UserViewModel {     public string MiddleName; } 
like image 131
Ermak Avatar answered Oct 15 '22 15:10

Ermak