Advertisement
Guest User

Untitled

a guest
Jan 21st, 2014
605
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.96 KB | None | 0 0
  1.     public abstract class BaseViewModel<TValidator> : IDataErrorInfo where TValidator : IValidator, new()
  2.     {
  3.         private readonly TValidator _validator = new TValidator();
  4.         private ValidationResult _validationResult;
  5.  
  6.         public BaseViewModel()
  7.         {
  8.             Validate();
  9.         }
  10.  
  11.         public virtual void Validate()
  12.         {
  13.             _validationResult = _validator.Validate(this);
  14.         }
  15.  
  16.         string IDataErrorInfo.this[string columnName]
  17.         {
  18.             get
  19.             {
  20.                 if (_validationResult == null || _validationResult.IsValid) return null;
  21.                 var ce = _validationResult.Errors.FirstOrDefault(x => x.PropertyName == columnName);
  22.                 return ce == null ? null : ce.ErrorMessage;
  23.             }
  24.         }
  25.  
  26.         public string Error
  27.         {
  28.             get
  29.             {
  30.                 if (_validationResult == null) return "Newer validated";
  31.                 if (_validationResult.IsValid) return null;
  32.                 return string.Join("\n", _validationResult.Errors.Select(x => x.ErrorMessage));
  33.             }
  34.         }
  35.  
  36.         public bool IsValid
  37.         {
  38.             get
  39.             {
  40.                 return ((IDataErrorInfo)this).Error == null;
  41.             }
  42.         }
  43.     }
  44.  
  45.     public class PersonViewModel : BaseViewModel<PersonViewModelValidator>
  46.     {
  47.         private string _name;
  48.         private int _age;
  49.  
  50.         public string Name  
  51.         {
  52.             get { return _name; }
  53.             set { _name = value; Validate();}
  54.         }
  55.  
  56.         public int Age
  57.         {
  58.             get { return _age; }
  59.             set { _age = value; Validate(); }
  60.         }
  61.     }
  62.  
  63.  
  64.     public class PersonViewModelValidator : AbstractValidator<PersonViewModel>
  65.     {
  66.         public PersonViewModelValidator()
  67.         {
  68.             RuleFor(x => x.Name).NotEmpty().Length(2, 200);
  69.             RuleFor(x => x.Age).GreaterThan(16);
  70.         }
  71.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement