【问题标题】:only min/max length should be validated仅应验证最小/最大长度
【发布时间】:2013-10-18 15:18:08
【问题描述】:

我在我的 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) 这样的黑客(不确定它是否有效)不适用。

【问题讨论】:

    标签: c# asp.net-mvc fluentvalidation


    【解决方案1】:

    你可以使用

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

    【讨论】:

      【解决方案2】:

      如果您只想检查最小长度:

      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&lt;T, string&gt; Length&lt;T&gt;(this IRuleBuilder&lt;T, string&gt; 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.");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多