ziggyx
ziggyx

Reputation: 33

MVC FluentValidation WithMessage using a property

When attempting to use a property in the WithMessage part of a fluent validation rule, the string property isn't used, and instead it just outputs true. I have used validation in other areas of the application using collections (which is less straight-forward), and I could perform this task without issues. The only difference here is that it's a single object with a base class.

Here is my validator:

public class MultiCulturalControlValidator : AbstractValidator<TitleMultiCulturalControlProperty>
{
    public MultiCulturalControlValidator()
    {
        RuleFor(x => x.EnglishValue).NotEmpty().WithMessage("test error {0}",  x => x.DisplayName);
    }
}

My viewmodel, with all the irrelevant properties stripped out:

[Validator(typeof(MultiCulturalControlValidator))]
[DataContract]
public class TitleMultiCulturalControlProperty : MultiCulturalControlProperty
{
    public TitleMultiCulturalControlProperty()
    {
    }

    /// <summary>
    /// Gets or sets the name of these culture table values.
    /// </summary>
    [DataMember]
    public string DisplayName { get; set; }

    /// <summary>
    /// Gets or sets the required english value.
    /// </summary>
    // ReSharper disable once LocalizableElement
    [Display(Name = "English")]
    [StringLength(255)]
    [DataMember]
    public override string EnglishValue { get; set; }
}

As you can see, the required English value is overridden. Is that the issue? The rule still runs correctly, though, and it's just the message that isn't correct.

The message that displays when the rule doesn't pass:

"test error true"

'true' should be the DisplayName string. I checked, and the name isn't null/empty when the data is posted. I've checked all over for help and I couldn't find anything covering this issue.

Thanks

Upvotes: 1

Views: 3747

Answers (2)

Drgnkght
Drgnkght

Reputation: 121

I know this is ancient, but I just found this question while searching for the solution to similar problem. Here is the syntax I ended up using (reworked for the original question).

public class MultiCulturalControlValidator : AbstractValidator<TitleMultiCulturalControlProperty>
{
    public MultiCulturalControlValidator()
    {
         RuleFor(x => x.EnglishValue).NotEmpty().WithMessage(x => string.Format("test error {0}",  x.DisplayName));
    }
}

Upvotes: 2

ozz
ozz

Reputation: 5366

Way too late of an answer, but I wonder if the fact you are inheriting from "MultiCulturalControlProperty" was the issue.

Upvotes: 0

Related Questions