我使用 Ninject、MVC4、AutoMapper 和 FluentValidation 粘合在一起。
我为我的视图模型编写了一个验证器,并且我编写了一个必须在视图模型验证器中调用的可重用验证器。
问题是当我发布表单时,没有在视图模型验证器上调用 Validate 覆盖,所以也没有调用可重用的验证器,所以最后 ModelResult 是有效的......(在编写实体时导致异常到数据库)...
奇怪的是,当我为其中一个属性添加 RuleFor 时,表单正在被很好地验证。
public class RequiredSourceViewModelValidator : AbstractValidator<RequiredSourceViewModel>
{
public RequiredSourceViewModelValidator()
{
Mapper.CreateMap<RequiredSourceViewModel, Source>();
}
public override FluentValidation.Results.ValidationResult Validate(RequiredSourceViewModel requiredSourceViewModel)
{
var validator = new SourceValidator();
var source = Mapper.Map<RequiredSourceViewModel, Source>(requiredSourceViewModel);
return validator.Validate(source);
}
}
public class SourceValidator : AbstractValidator<Source>
{
public SourceValidator()
{
RuleFor(s => s.Name)
.NotEmpty()
.WithMessage("Naam mag niet leeg zijn.")
.Length(1, 100)
.WithMessage("Naam mag niet langer zijn dan 100 karakters.");
RuleFor(s => s.Url)
.NotEmpty()
.WithMessage("Url mag niet leeg zijn.")
.Must(BeAValidUrl)
.WithMessage("Url is niet geldig.")
.Length(1, 100)
.WithMessage("Url mag niet langer zijn dan 100 karakters.");
}
private bool BeAValidUrl(string url)
{
if (url == null)
{
return true;
}
var regex = new Regex(@"^http(s)?://([\w-]+.)+[\w-]+(/[\w- ./?%&=])?$");
return regex.IsMatch(url);
}
}
public class Source : IEntity
{
/// <summary>
/// Gets or sets the primary key of the source.
/// </summary>
public int Id { get; set; }
/// <summary>
/// Gets or sets the name of the source.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets or sets the url of the source.
/// </summary>
public string Url { get; set; }
/// <summary>
/// Gets or sets the ordinal of the source.
/// </summary>
/// <value>
/// The ordinal of the source.
/// </value>
public int Ordinal { get; set; }
public int? GameId { get; set; }
}
这里有什么问题?