流利的验证不适用于长度

时间:2011-01-17 13:59:49

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

我正在尝试让Fluent验证在我的客户端验证上正常工作。我正在使用ASP.NET MVC 3。

我有一个必需的标题,它必须在1到100个字符之间。因此,当我输入标题时,会显示一条错误消息,该消息不在我的规则集中。这是我的规则集:

RuleFor(x => x.Title)
   .NotEmpty()
   .WithMessage("Title is required")
   .Length(1, 100)
   .WithMessage("Title must be less than or equal to 100 characters");

以下是显示的错误消息:

Please enter a value less than or equal to 100

我不确定我做错了什么。这是我的global.asax:

// FluentValidation
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;

ModelValidatorProviders.Providers.Clear();
ModelValidatorProviders.Providers.Add(
   new FluentValidationModelValidatorProvider(new AttributedValidatorFactory()));

ModelMetadataProviders.Current = new FluentValidationModelMetadataProvider(
   new AttributedValidatorFactory());

1 个答案:

答案 0 :(得分:12)

对我来说很好。以下是步骤:

  1. 使用默认的Visual Studio模板
  2. 创建一个新的ASP.NET MVC 3 RTM项目
  3. 下载最新的FluentValidation.NET
  4. 引用FluentValidation.dllFluentValidation.Mvc.dll程序集(注意.zip中有两个文件夹:MVC2和MVC3,所以一定要选择正确的程序集)
  5. 添加模型:

    [Validator(typeof(MyViewModelValidator))]
    public class MyViewModel
    {
        public string Title { get; set; }
    }
    

    和相应的验证器:

    public class MyViewModelValidator : AbstractValidator<MyViewModel>
    {
        public MyViewModelValidator()
        {
            RuleFor(x => x.Title)
               .NotEmpty()
               .WithMessage("Title is required")
               .Length(1, 5)
               .WithMessage("Title must be less than or equal to 5 characters");
        }
    }
    

    添加到Application_Start

    DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
    
    ModelValidatorProviders.Providers.Clear();
    ModelValidatorProviders.Providers.Add(
        new FluentValidationModelValidatorProvider(new AttributedValidatorFactory()));
    
    ModelMetadataProviders.Current = new FluentValidationModelMetadataProvider(
        new AttributedValidatorFactory());
    

    添加控制器:

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View(new MyViewModel());
        }
    
        [HttpPost]
        public ActionResult Index(MyViewModel model)
        {
            return View(model);
        }
    }
    

    和相应的观点:

    @model SomeApp.Models.MyViewModel
    @{
        ViewBag.Title = "Home Page";
    }
    <script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
    @using (Html.BeginForm())
    {
        @Html.TextBoxFor(x => x.Title)
        @Html.ValidationMessageFor(x => x.Title)
        <input type="submit" value="OK" />
    }
    

    现在尝试提交表格,留下标题输入为空=&gt;客户端验证启动并显示标题是必需的消息。现在开始键入一些text =&gt;错误消息消失。在输入框中键入超过5个字符后,标题必须小于或等于5个字符验证消息出现。所以一切似乎都按预期工作。