Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public abstract class BaseViewModel<TValidator> : IDataErrorInfo where TValidator : IValidator, new()
- {
- private readonly TValidator _validator = new TValidator();
- private ValidationResult _validationResult;
- public BaseViewModel()
- {
- Validate();
- }
- public virtual void Validate()
- {
- _validationResult = _validator.Validate(this);
- }
- string IDataErrorInfo.this[string columnName]
- {
- get
- {
- if (_validationResult == null || _validationResult.IsValid) return null;
- var ce = _validationResult.Errors.FirstOrDefault(x => x.PropertyName == columnName);
- return ce == null ? null : ce.ErrorMessage;
- }
- }
- public string Error
- {
- get
- {
- if (_validationResult == null) return "Newer validated";
- if (_validationResult.IsValid) return null;
- return string.Join("\n", _validationResult.Errors.Select(x => x.ErrorMessage));
- }
- }
- public bool IsValid
- {
- get
- {
- return ((IDataErrorInfo)this).Error == null;
- }
- }
- }
- public class PersonViewModel : BaseViewModel<PersonViewModelValidator>
- {
- private string _name;
- private int _age;
- public string Name
- {
- get { return _name; }
- set { _name = value; Validate();}
- }
- public int Age
- {
- get { return _age; }
- set { _age = value; Validate(); }
- }
- }
- public class PersonViewModelValidator : AbstractValidator<PersonViewModel>
- {
- public PersonViewModelValidator()
- {
- RuleFor(x => x.Name).NotEmpty().Length(2, 200);
- RuleFor(x => x.Age).GreaterThan(16);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement