Fluent 验证不适用于长度
我正在尝试让 Fluent Validation 在我的客户端验证上正常工作。我正在使用 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());
I am trying to get Fluent Validation to work correctly on my client side validation. I am using ASP.NET MVC 3.
I have a title that is required and it must be between 1 and 100 characters long. So while I am typing in the title an error message displays that is not in my ruleset. Here is my rule set:
RuleFor(x => x.Title)
.NotEmpty()
.WithMessage("Title is required")
.Length(1, 100)
.WithMessage("Title must be less than or equal to 100 characters");
Here is the error message that is displayed:
Please enter a value less than or equal to 100
I'm not sure what I am doing wrong. Here is my global.asax:
// FluentValidation
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
ModelValidatorProviders.Providers.Clear();
ModelValidatorProviders.Providers.Add(
new FluentValidationModelValidatorProvider(new AttributedValidatorFactory()));
ModelMetadataProviders.Current = new FluentValidationModelMetadataProvider(
new AttributedValidatorFactory());
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对我来说效果很好。步骤如下:
FluentValidation.dll
和FluentValidation.Mvc.dll
程序集(请注意 .zip 中有两个文件夹:MVC2 和 MVC3,因此请确保选择正确的程序集)模型:
和相应的验证器:
添加到
Application_Start
:添加控制器:
和相应的视图:
现在尝试提交表单,将标题输入留空 =>客户端验证启动,并显示 标题为必填项 消息。现在开始输入一些文本 =>错误消息消失。一旦您在输入框中输入超过 5 个字符,就会出现标题必须小于或等于 5 个字符验证消息。所以一切似乎都按预期进行。
Works fine for me. Here are the steps:
FluentValidation.dll
andFluentValidation.Mvc.dll
assemblies (be careful there are two folders inside the .zip: MVC2 and MVC3 so make sure to pick the proper assembly)Add a model:
and a corresponding validator:
Add to
Application_Start
:Add a controller:
and the corresponding view:
Now try to submit the form leaving the Title input empty => client side validation kicks in and the Title is required message is shown. Now start typing some text => the error message disappears. Once you type more than 5 characters in the input box the Title must be less than or equal to 5 characters validation message appears. So everything seems to work as expected.