Skip to content

Validation

Arnel Robles edited this page Sep 28, 2026 · 1 revision

Package 4: Mapsicle.Validation

Post-mapping validation using FluentValidation, validate DTOs immediately after mapping.

Basic Usage

using FluentValidation;
using Mapsicle.Fluent;
using Mapsicle.Validation;

// 1. Define your validator
public class UserDtoValidator : AbstractValidator<UserDto>
{
    public UserDtoValidator()
    {
        RuleFor(x => x.Name).NotEmpty().WithMessage("Name is required");
        RuleFor(x => x.Email).NotEmpty().EmailAddress();
        RuleFor(x => x.Age).GreaterThan(0).WithMessage("Age must be positive");
    }
}

// 2. Map and validate in one call
var result = mapper.MapAndValidate<User, UserDto, UserDtoValidator>(user);

if (result.IsValid)
{
    return Ok(result.Value);  // The mapped DTO
}
else
{
    return BadRequest(result.ErrorsByProperty);  // { "Email": ["Valid email is required"] }
}

API Overview

// Map and validate with validator type
var result = mapper.MapAndValidate<TSource, TDest, TValidator>(source);

// Map and validate with validator instance
var validator = new UserDtoValidator();
var result = mapper.MapAndValidate<UserDto>(source, validator);

// Validate an existing object
var result = dto.Validate<UserDto, UserDtoValidator>();

// Get value or throw exception
var dto = result.GetValueOrThrow();  // Throws ValidationException if invalid

Result Properties

result.IsValid           // bool - true if validation passed
result.Value             // TDest - the mapped object
result.Errors            // IList<ValidationFailure> - all validation errors
result.ErrorsByProperty  // IDictionary<string, string[]> - errors grouped by property
result.ValidationResult  // FluentValidation.Results.ValidationResult - full result

Real-World Example: API Controller

[ApiController]
[Route("api/users")]
public class UsersController : ControllerBase
{
    private readonly IMapper _mapper;
    private readonly IUserRepository _repo;

    public UsersController(IMapper mapper, IUserRepository repo)
    {
        _mapper = mapper;
        _repo = repo;
    }

    [HttpPost]
    public async Task<IActionResult> Create([FromBody] CreateUserRequest request)
    {
        var result = _mapper.MapAndValidate<CreateUserRequest, UserDto, UserDtoValidator>(request);

        if (!result.IsValid)
        {
            return BadRequest(new { errors = result.ErrorsByProperty });
        }

        var user = await _repo.CreateAsync(result.Value);
        return CreatedAtAction(nameof(GetById), new { id = user.Id }, user);
    }
}

Clone this wiki locally