C#C
C#13mo ago
Cydo

How can I make FluentValidation return errors in camel case??

I have tried created an ValidationInterceptor and configuring my program.cs to return json in camel case but nothing seems to work

using FluentValidation;
using FluentValidation.Results;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using System.Text.Json;
using FluentValidation.AspNetCore;

namespace CollabParty.Application.Common.Validators
{
    public class CamelCaseValidationInterceptor : IValidatorInterceptor
    {
        // Before MVC validation
        public ValidationContext<T> BeforeMvcValidation<T>(ControllerContext controllerContext, ValidationContext<T> context)
        {
            return context; // No changes before validation
        }

        // After MVC validation: Convert the property names to camelCase
        public ValidationResult AfterMvcValidation<T>(ControllerContext controllerContext, ValidationContext<T> context, ValidationResult result)
        {
            var camelCasedErrors = result.Errors.Select(error =>
                new ValidationFailure(
                    JsonNamingPolicy.CamelCase.ConvertName(error.PropertyName), // Convert to camelCase
                    error.ErrorMessage,
                    error.AttemptedValue)
                {
                    ErrorCode = error.ErrorCode,
                    CustomState = error.CustomState,
                    Severity = error.Severity
                }).ToList();

            return new ValidationResult(camelCasedErrors);
        }

        // These methods are not needed but can be left as no-ops
        public IValidationContext BeforeAspNetValidation(ActionContext actionContext, IValidationContext commonContext)
        {
            return commonContext;
        }

        public ValidationResult AfterAspNetValidation(ActionContext actionContext, IValidationContext validationContext, ValidationResult result)
        {
            return result;
        }
    }
}
Was this page helpful?