문제

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.

도움이 되었습니까?

해결책

You can use

RuleFor(x => x.ProductName).NotEmpty().WithMessage("Name required")
            .Length(10);

to get the message

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

if you want a check for min and max length

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

다른 팁

If you want to check for Min Length only:

RuleFor(x => x.Name).NotEmpty().WithMessage("Name required")
    .Length(10)
    .WithMessage("Name should have at least 10 chars.");

If you want to check for Max Length only:

RuleFor(x => x.Name).NotEmpty().WithMessage("Name required")
    .Length(0, 15)
    .WithMessage("Name should have 15 chars at most.");

This is the API documentation for the second one (public static IRuleBuilderOptions<T, string> Length<T>(this IRuleBuilder<T, string> ruleBuilder, int min, int max)):

Summary: Defines a length validator on the current rule builder, but only for string properties. Validation will fail if the length of the string is outside of the specifed range. The range is inclusive.

Parameters:

ruleBuilder: The rule builder on which the validator should be defined

min:

max:

Type parameters:

T: Type of object being validated

You could also create an extension like this (using Must instead of 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);
        }
    }
}

And use it like this:

RuleFor(x => x.Name).NotEmpty().WithMessage("Name required")
    .MaxLength(15)
    .WithMessage("Name should have 15 chars at most.");
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top