2013-10-18 122 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.");