Leito7
Leito7

Reputation: 1

Fluent validation: It is possible to add more error messages?

I have error model, for example

and rule in my validator

RuleFor(d => d.Name).NotEmpty().WithMessage("{PropertyName} is required.")

Is there any way to add a new custom option such as

 RuleFor(d => d.Name).NotEmpty().WithMessage("{PropertyName} is required.").**WithCustomErrorMessage("Example message content")**?

EDIT: I want return list of errors from my web api app. Every error looks something like this:

public class Error
    {
        public string ErrorName{ get; set; }
        public string ErrorDetails{ get; set; }
        public string ErrorCode{ get; set; }
        public string FieldPath{ get; set; }
    }

I would like to assign these values in the validator and then create a list of errors in my handler using the ValidationResult object.

Thank you for your advices.

Upvotes: -1

Views: 2752

Answers (3)

AMunim
AMunim

Reputation: 1161

You can return custom error object with WithState, for example:

RuleFor(x => x.Ledger.LedgerDetails)
            .NotEmpty()
            .WithState(x => Result<string>.Failure(new InvalidGeneralLedgerException("Can't add an empty ledger")))

Here Result is my custom object, in your case you can do

WithState(x => new Error() { ErrorName = "My custom prop name", ErrorCode = 69 })

This will return your custom object when the rule breaks.

Upvotes: 0

joseph rozario
joseph rozario

Reputation: 55

Here I tried

  public async Task OnActionExecutionAsync(ActionExecutingContext context,
                                       ActionExecutionDelegate next)
        {
            if (!context.ModelState.IsValid)
            {
                var errors = context.ModelState.Values.Where(v => v.Errors.Count > 0)
                        .SelectMany(v => v.Errors)
                        .Select(v => v.ErrorMessage)
                        .ToList();

                var value = context.ModelState.Keys.ToList();
                Dictionary<string, string[]> dictionary = new Dictionary<string, string[]>();
                foreach (var modelStateKey in context.ModelState.Keys.ToList())
                {   
                   // here you can get your desire data
                    string[] arr = null ;
                    List<string> list = new List<string>();
                    foreach (var error in context.ModelState[modelStateKey].Errors)
                    {
                        // here you can modify as you want 
                        list.Add(error.ErrorMessage);
                    }
                    arr = list.ToArray();
                    dictionary.Add(modelStateKey, arr);
                }
                // here you can make your own model and bind data as you want.
                var responseObj = new 
                {
                    StatusCode="400",
                    Message = "Bad Request",
                    Errors = dictionary
                };
 

        context.Result = new BadRequestObjectResult(responseObj);
                return;
            }
            await next(); 
        }

Response Model example:// you can make your own model
{
    "statusCode": "400",
    "message": "Bad Request",
    "errors": {
        "Channel": [
            "'Channel' must not be empty."
        ],
        "TransactionId": [
            "'TransactionId' must not be empty."
        ],
        "Number": [
            "'Number' must not be empty."
        ]
    }
}

Upvotes: 0

Rule
Rule

Reputation: 325

Why don’t you just edit the property inside ‘.WithMessage()’? Edit:

As you now edited the question, i will add the answer here. Just to be clear you are missing some code on how you call your validator. That is needed to properly answer your question.

Making the assumption you want to return all errors here and that is in fact possible. Look at this link to retrieve all errors from the validation https://docs.fluentvalidation.net/en/latest/error-codes.html

Upvotes: 1

Related Questions