c# - 只应验证最小/最大长度

标签 c# asp.net-mvc fluentvalidation

我在我的 ASP.NET MVC 4 项目中使用 FluentValidation 框架进行服务器端和客户端验证。
有没有本地 (非黑客)仅使用最大长度或仅最小长度验证字符串长度的方法?
例如这种方式:

var isMinLengthOnly = true;
var minLength = 10;
RuleFor(m => m.Name)
    .NotEmpty().WithMessage("Name required")
    .Length(minLength, isMinLengthOnly);
默认错误消息模板不应该'Name' must be between 10 and 99999999 characters. You entered 251 characters.'Name' must be longer than 10 characters. You entered 251 characters.并且应该支持客户端属性,例如黑客喜欢 RuleFor(m => m.Name.Length).GreaterThanOrEqual(minLength) (不确定它是否有效)不适用。

最佳答案

您可以使用

RuleFor(x => x.ProductName).NotEmpty().WithMessage("Name required")
            .Length(10);

获取消息
'Name' must be longer 10 characters. You entered 251 characters.

如果你想检查最小和最大长度
RuleFor(x => x.Name).NotEmpty().WithMessage("Name required")
                    .Must(x => x.Length > 10 && x.Length < 15)
                    .WithMessage("Name should be between 10 and 15 chars");

关于c# - 只应验证最小/最大长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19453174/

相关文章:

c# - 如何在将 Excel 导入 SQL Server 时插入日期

c# - 程序在调试时崩溃

asp.net-mvc - 如何在Asp.net MVC中分离登录 View ?

asp.net - 数据传输对象、业务对象、域对象还是其他对象?

javascript - 将服务器(c#/Razor)值传递到 AngularJS 应用程序的最佳方法

asp.net - 发送 IEnumerable<T> 时对 EditorTemplate 进行客户端不显眼的验证

c# - 有没有办法让 FluentValidation 更动态?

c# - 如何将服务器数据库复制到我的本地机器以生成脚本

c# - 使用 RuleForEach 时如何访问正在验证的集合项?

c# - 该事件只能出现在 += 或 -= 错误的左侧