1
我調試所有,並注意到,該驗證調用構造函數(而不是一個時間,那奇怪)。那是我的IoC工廠正常工作。 與服務電話(與規則集的規則)定製的檢驗工作正常(我調試 - 電話製造)。但是標準驗證規則(NotEmpty,Length,Matches和Must for Categories屬性)不起作用 - ModelState對象中沒有驗證錯誤。流利驗證不工作
這一切運作初期,我沒有更改任何張貼在這裏的代碼。沒有改變/添加全局模型粘合劑。我沒有想法。
爲模型的代碼以非工作驗證:
我的後作用:
[HttpPost]
public ActionResult CreateTest([CustomizeValidator(RuleSet = "New")] Test model)
{
if (ModelState.IsValid)
{
var testId = testService.CreateTest(model);
return RedirectToAction("Test", new { testId });
}
PrepareTestEdit(true);
return View("EditTest");
}
我的模型:
[Validator(typeof(TestValidator))]
public class Test
{
public Test()
{
Categories = new List<string>();
}
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string UrlName { get; set; }
public List<string> Categories { get; set; }
}
驗證:
public class TestValidator : AbstractValidator<Test>
{
public TestValidator(ITestService testService)
{
RuleSet("Edit",() =>
{
RuleFor(x => x.Title).
Must((model, title) => testService.ValidateTitle(title, model.Id)).WithMessage("1");
RuleFor(x => x.UrlName).
Must((model, urlName) => testService.ValidateUrlName(urlName, model.Id)).WithMessage("2");
});
RuleSet("New",() =>
{
RuleFor(x => x.Title).
Must(title => testService.ValidateTitle(title)).WithMessage("3");
RuleFor(x => x.UrlName).
Must(urlName => testService.ValidateUrlName(urlName)).WithMessage("4");
});
RuleFor(x => x.Title).
NotEmpty().WithMessage("5").
Length(1, 100).WithMessage("6");
RuleFor(x => x.UrlName).
NotEmpty().WithMessage("7").
Length(1, 100).WithMessage("8").
Matches("^[-_a-zA-Z0-9]*$").WithMessage("9");
RuleFor(x => x.Description).
NotEmpty().WithMessage("10");
RuleFor(x => x.Categories).
Must(categories => categories != null && categories.Any()).WithMessage("11");
}
}