2011-01-20 17 views
19

Utilicé Validador fluido. Pero a veces necesito crear una jerarquía de reglas. Por ejemplo:Validaciones fluidas. Heredar clases de validación

[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;  
} 

quiero heredar las reglas de validación de UserValidation a RootValidation. Pero este código no funcionó:

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

¿Cómo puedo heredar la clase de validación con FluentValidation?

Respuesta

29

Para resolver esto, debe cambiar la clase UserValidation por genérica. Vea el código a continuación.

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; 
} 
+0

Intentaré hacer UserValidation abstract. ¡Pero ya es grandioso! ¡Gracias! –

Cuestiones relacionadas