user2232861
user2232861

Reputation: 283

Fluent Validation Complex Property message shows Complex Property Name in it

Hi I have class structure like this

public class Order
{
   public Address OfficeAddress {get;set;}
}

public class Address
{
  public string ID {get;set;}
  public string Street1 {get;set;}
  public string street2 {get;set;}
  public string City {get;set;}
  public string State {get;set;}
  public string ZipCode {get;set;}
}

I have validator for Order as below

public OrderValidator : AbstractValidator<Order>
{
  public OrderValidator()
  {
        Custom(Order =>
        {
            //Did some custom validation...works fine.
        });

    RuleFor(o => o.OfficeAddress.StreetLine1)
                 .Cascade(CascadeMode.StopOnFirstFailure)
                 .NotEmpty().WithLocalizedMessage(() => Myresource.required)
                 .Length(1, 60).WithLocalizedMessage(() => Myresource.maxLength)
                 .Unless(o => null == o.OfficeAddress);
  }
}

My message show like this

 Office Address. Street Line1 is required

why does it append "Office Address. " and why it have splitted the property names ? My resources message is like this {PropertyName} is required. Now how can I tell it to not show me "Office Address. " and do not split it.

I have similar complex address properties in other views but it works fine there and I am not sure why. The only differnce is that all other validators have RuleSet defined and inside them I validate address similary but here above it is not in RuleSet. Here for this View in controller Post Action method even I did not mention [CustomizeValidator(RuleSet = "RuleSetName")] as i have Custom validation above. Not sure if that is the problem.

Even If I decide to use RuleSet then can i have "RuleSet" as well as Custom Validator in same Validator ? if yes then what should i name RuleSet as "Address"? and mark the Action MEthod with same name and it will call both Custom as well as "Address" RuleSet ?

Upvotes: 0

Views: 1137

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038930

You should define a separate validator for the Address class:

public class AddressValidator: AbstractValidator<Address>
{
    public void AddressValidator()
    {
        this
            .RuleFor(o => o.StreetLine1)
            .Cascade(CascadeMode.StopOnFirstFailure)
            .NotEmpty().WithLocalizedMessage(() => Myresource.required)
            .Length(1, 60).WithLocalizedMessage(() => Myresource.maxLength)
            .Unless(o => null == o);
    }
}

and then in your OrderValidator:

public OrderValidator : AbstractValidator<Order>
{
    public OrderValidator()
    {
        Custom(Order =>
        {
            //Did some custom validation...works fine.
        });

        this
            .RuleFor(o => o.OfficeAddress)
            .SetValidator(new AddressValidator());
    }
}

Upvotes: 2

Related Questions