流畅的验证不起作用

时间:2012-03-26 19:56:06

标签: asp.net-mvc asp.net-mvc-3 fluentvalidation

我调试了所有并注意到,调用了验证器构造函数(而不是一次,奇怪的是)。那是我的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");
    }
}

1 个答案:

答案 0 :(得分:0)

Fluent validation documentation

  

RuleSet允许您将验证规则组合在一起,这些规则可以作为一个组一起执行,而忽略其他规则

我将所有通用规则放在单独的私有方法中,并为匿名函数体中的两个规则集调用它。