public class FluentModelValidator<T> : IModelValidator<T>
{
private readonly IValidator<T> validator;
private T _subject;
public FluentModelValidator(IValidator<T> validator)
{
this.validator = validator;
}
public void Initialize(object subject)
{
this._subject = (T)subject;
}
public async Task<IEnumerable<string>> ValidatePropertyAsync(string propertyName)
{
// If someone's calling us synchronously, and ValidationAsync does not complete synchronously,
// we'll deadlock unless we continue on another thread.
return (await this.validator.ValidateAsync(this._subject, CancellationToken.None, propertyName).ConfigureAwait(false))
.Errors.Select(x => x.ErrorMessage);
}
public async Task<Dictionary<string, IEnumerable<string>>> ValidateAllPropertiesAsync()
{
// If someone's calling us synchronously, and ValidationAsync does not complete synchronously,
// we'll deadlock unless we continue on another thread.
return (await this.validator.ValidateAsync(this._subject).ConfigureAwait(false))
.Errors.GroupBy(x => x.PropertyName)
.ToDictionary(x => x.Key, x => x.Select(failure => failure.ErrorMessage));
}
}
public class LoginViewModelValidator : AbstractValidator<LoginViewModel>
{
public LoginViewModelValidator()
{
RuleFor(x => x.PhoneNumber).NotEmpty().Length(11).WithMessage("请输入正确的手机号");
}
}
protected override void OnValidationStateChanged(IEnumerable<string> changedProperties)
{
base.OnValidationStateChanged(changedProperties);
// Fody can't weave other assemblies, so we have to manually raise this
this.NotifyOfPropertyChange(() => this.CanSubmit);
}
public bool CanSubmit => !this.HasErrors;
public async void Submit()
{
if (await this.ValidateAsync())
{
MessageBox.Show(”success“);
}
}