Skip to content

Instantly share code, notes, and snippets.

@dealproc
Created January 31, 2015 10:59
Show Gist options
  • Save dealproc/ec0bfbf0df55f06b3f22 to your computer and use it in GitHub Desktop.
Save dealproc/ec0bfbf0df55f06b3f22 to your computer and use it in GitHub Desktop.
Validation using https://fluentvalidation.codeplex.com/wikipage?title=mvc in WPF and Caliburn Micro
namespace {Product}.Infrastructure.Framework {
using FluentValidation;
using FluentValidation.Results;
using System;
using System.Text;
public static class ValidationHelper {
public static ValidationResult Validate<T, K>(K entity)
where T : IValidator<K>, new()
where K : class {
IValidator<K> __Validator = new T();
return __Validator.Validate(entity);
}
public static string GetError(ValidationResult result) {
var __ValidationErrors = new StringBuilder();
foreach (var failure in result.Errors) {
__ValidationErrors.Append(failure.ErrorMessage);
__ValidationErrors.Append(Environment.NewLine);
}
return __ValidationErrors.ToString();
}
}
}
namespace {Product}.Infrastructure.Framework {
using Caliburn.Micro;
using FluentValidation;
using FluentValidation.Results;
using System.ComponentModel;
using System.Linq;
public class ValidationScreen<TValidator, TViewModel> : Screen, IDataErrorInfo
where TValidator : IValidator<TViewModel>, new()
where TViewModel : ValidationScreen<TValidator, TViewModel> {
bool _IsDirty = false;
public bool IsDirty {
get { return _IsDirty; }
protected set {
_IsDirty = value;
NotifyOfPropertyChange(() => IsDirty);
}
}
public bool IsValid {
get { return SelfValidate().IsValid; }
}
public ValidationResult SelfValidate() {
TViewModel viewModel = (TViewModel)this;
return ValidationHelper.Validate<TValidator, TViewModel>(viewModel);
}
public string Error {
get { return ValidationHelper.GetError(SelfValidate()); }
}
public string this[string columnName] {
get {
var validationResults = SelfValidate();
if (validationResults == null) {
return string.Empty;
}
var columnResult = validationResults.Errors.FirstOrDefault<ValidationFailure>(x => string.Compare(x.PropertyName, columnName, true) == 0);
return columnResult != null ? columnResult.ErrorMessage : string.Empty;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment