2
RuleFor(getEligibleShippingDetails => getEligibleShippingDetails.ShipFromAddress)
 .NotNull()
 .WithMessage("Ship from address is required.")
 .SetValidator(shippingFromAddressValidator.FluentValidator)

The exception I'm getting is

Exception : Invalid get eligible shipping services request. 'Email' must not be empty. Email address is required.

The message doesn't include that it was actually validation of ShipFromAddress property.

Of course I can pass a reference message to the child validator like "Ship from address", however, maybe there is a more elegant way to do it.

Tried something like that,

RuleFor(getEligibleShippingDetails => getEligibleShippingDetails.ShipFromAddress)
.NotNull()
.WithMessage("Ship from address is required.")
.SetValidator(shippingFromAddressValidator.FluentValidator)
.WithMessage("Invalid ship from address.")

However the last message was ignored.

Any advise.

schizofreindly
  • 177
  • 2
  • 13

1 Answers1

0

Child model should have a reference to parent model, because there are no special means in FlueentValidation for this purpose:

public class Parent
{
    public int Id {get;set;}
    public Child ChildModel {get;set;}
}

public class Child
{
    public string Name {get;set;}
    public Parent ParentModel {get;set;}
}

public class ChildValidator : AbstractValidator<Child>
{
    public ChildValidator()
    {
        RuleFor(x => x.Name)
            .NotNull()
            .WithMessage("Name should not be null for child of {0}'s parent", (model, value) => model.Parent.Id)
    }
}

If you use MVC - just implement ModelBinder, that would set Parent property for child.

David Levin
  • 6,573
  • 5
  • 48
  • 80