2012-03-26 90 views
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"); 
    } 
} 

回答

0

Fluent validation documentation

规则集允许你组验证规则一起可以在一起,同时忽略其他规则

被执行作为一组予放置所有的共同规则以分离私有方法并调用它两个规则集在匿名函数体中。