How to check Minlength and Maxlength validation of a property in C# using Fluent Validation?

FluentValidation is a popular .NET validation library that provides an easy way to validate model properties. The MinLength and MaxLength validators ensure that string properties meet specific length requirements, making them essential for input validation scenarios.

Syntax

Following is the syntax for using MaximumLength validator −

RuleFor(x => x.PropertyName).MaximumLength(maxValue);

Following is the syntax for using MinimumLength validator −

RuleFor(x => x.PropertyName).MinimumLength(minValue);

MaxLength Validator

The MaximumLength validator ensures that the length of a string property does not exceed the specified maximum value. This validator is only valid on string properties.

The following format arguments are available for custom error messages −

  • {PropertyName} − The name of the property being validated
  • {MaxLength} − Maximum allowed length
  • {TotalLength} − Actual number of characters entered
  • {PropertyValue} − The current value of the property

MinLength Validator

The MinimumLength validator ensures that the length of a string property meets or exceeds the specified minimum value. Like MaximumLength, this validator is only valid on string properties.

The following format arguments are available for custom error messages −

  • {PropertyName} − The name of the property being validated
  • {MinLength} − Minimum required length
  • {TotalLength} − Actual number of characters entered
  • {PropertyValue} − The current value of the property

Basic MinLength and MaxLength Example

using System;
using System.Collections.Generic;
using FluentValidation;
using FluentValidation.Results;

public class PersonModel {
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class PersonValidator : AbstractValidator<PersonModel> {
    public PersonValidator() {
        RuleFor(p => p.FirstName).MaximumLength(7).WithMessage("MaximumLength must be 7 {PropertyName}");
        RuleFor(p => p.LastName).MinimumLength(5).WithMessage("MinimumLength must be 5 {PropertyName}");
    }
}

class Program {
    static void Main(string[] args) {
        List<string> errors = new List<string>();

        PersonModel person = new PersonModel();
        person.FirstName = "TestUser444";
        person.LastName = "TTT";

        PersonValidator validator = new PersonValidator();
        ValidationResult results = validator.Validate(person);

        if (results.IsValid == false) {
            foreach (ValidationFailure failure in results.Errors) {
                errors.Add(failure.ErrorMessage);
            }
        }

        foreach (var item in errors) {
            Console.WriteLine(item);
        }
    }
}

The output of the above code is −

MaximumLength must be 7 First Name
MinimumLength must be 5 Last Name

Using Built-in Error Messages

FluentValidation provides default error messages with placeholder tokens. Here's an example using the built-in messages −

using System;
using FluentValidation;
using FluentValidation.Results;

public class UserModel {
    public string Username { get; set; }
    public string Password { get; set; }
}

public class UserValidator : AbstractValidator<UserModel> {
    public UserValidator() {
        RuleFor(x => x.Username).MinimumLength(3).MaximumLength(15);
        RuleFor(x => x.Password).MinimumLength(8);
    }
}

class Program {
    static void Main(string[] args) {
        UserModel user = new UserModel {
            Username = "AB",
            Password = "123"
        };

        UserValidator validator = new UserValidator();
        ValidationResult result = validator.Validate(user);

        if (!result.IsValid) {
            foreach (var error in result.Errors) {
                Console.WriteLine($"{error.PropertyName}: {error.ErrorMessage}");
            }
        }
    }
}

The output of the above code is −

Username: The length of 'Username' must be at least 3 characters. You entered 2 characters.
Password: The length of 'Password' must be at least 8 characters. You entered 3 characters.

Combining MinLength and MaxLength

You can chain both validators on the same property to enforce a length range −

using System;
using FluentValidation;
using FluentValidation.Results;

public class ProductModel {
    public string ProductName { get; set; }
    public string Description { get; set; }
}

public class ProductValidator : AbstractValidator<ProductModel> {
    public ProductValidator() {
        RuleFor(x => x.ProductName)
            .MinimumLength(2)
            .MaximumLength(50)
            .WithMessage("Product name must be between 2 and 50 characters");
            
        RuleFor(x => x.Description)
            .MinimumLength(10)
            .MaximumLength(200);
    }
}

class Program {
    static void Main(string[] args) {
        ProductModel product = new ProductModel {
            ProductName = "A",
            Description = "Short"
        };

        ProductValidator validator = new ProductValidator();
        ValidationResult result = validator.Validate(product);

        if (!result.IsValid) {
            foreach (var error in result.Errors) {
                Console.WriteLine($"{error.PropertyName}: {error.ErrorMessage}");
            }
        }
    }
}

The output of the above code is −

ProductName: Product name must be between 2 and 50 characters
Description: The length of 'Description' must be at least 10 characters. You entered 5 characters.

Conclusion

FluentValidation's MinimumLength and MaximumLength validators provide a clean and flexible way to enforce string length constraints. They can be used individually or combined to create length ranges, with customizable error messages and built-in placeholder tokens for dynamic validation feedback.

Updated on: 2026-03-17T07:04:36+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements