3

I use FluentValidation framework in my ASP.NET MVC 4 project for both server-side and client-side validation.

Is there native (non-hack) way to validate string length with only max length, or only min length?

For example this way:

var isMinLengthOnly = true;
var minLength = 10;
RuleFor(m => m.Name)
    .NotEmpty().WithMessage("Name required")
    .Length(minLength, isMinLengthOnly);

default error message template should be not

'Name' must be between 10 and 99999999 characters. You entered 251 characters.

but

'Name' must be longer than 10 characters. You entered 251 characters.

And client-side attributes should be supported, e.g. hacks like RuleFor(m => m.Name.Length).GreaterThanOrEqual(minLength) (not sure if it works) not applicable.

4

2 回答 2

12

您可以使用

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");
于 2014-01-28T22:45:50.347 回答
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.");
于 2017-05-10T18:22:28.067 回答