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?
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With