我在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 10 characters. You entered 251 characters.
应支持客户端属性,例如像RuleFor(m => m.Name.Length).GreaterThanOrEqual(minLength)
这样的黑客(不确定它是否有效)不适用。
答案 0 :(得分:10)
您可以使用
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");
答案 1 :(得分:0)
如果您只想检查最小长度:
RuleFor(x => x.Name).NotEmpty().WithMessage("Name required")
.Length(10)
.WithMessage("Name should have at least 10 chars.");
如果您只想检查最大长度:
RuleFor(x => x.Name).NotEmpty().WithMessage("Name required")
.Length(0, 15)
.WithMessage("Name should have 15 chars at most.");
这是第二个(public static IRuleBuilderOptions<T, string> Length<T>(this IRuleBuilder<T, string> ruleBuilder, int min, int max)
)的API文档:
摘要:在当前规则构建器上定义长度验证程序,但仅限于字符串属性。如果字符串的长度超出指定范围,则验证将失败。范围包容。
<强>参数:强>
ruleBuilder:应在其上定义验证程序的规则构建器
分:
最大:
输入参数:
T: 正在验证的对象类型
您还可以创建这样的扩展程序(使用Must
代替Length
):
using FluentValidation;
namespace MyProject.FluentValidationExtensiones
{
public static class Extensiones
{
public static IRuleBuilderOptions<T, string> MaxLength<T>(this IRuleBuilder<T, string> ruleBuilder, int maxLength)
{
return ruleBuilder.Must(x => string.IsNullOrEmpty(x) || x.Length <= maxLength);
}
}
}
并像这样使用它:
RuleFor(x => x.Name).NotEmpty().WithMessage("Name required")
.MaxLength(15)
.WithMessage("Name should have 15 chars at most.");