2013-10-18 120 views
2

我在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.

和客户端的属性应该是suppo例如,像RuleFor(m => m.Name.Length).GreaterThanOrEqual(minLength)(不知道它是否有效)不适用。

回答

9

您可以使用

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"); 
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.");