jrummell
jrummell

Reputation: 43117

Unobtrusive client validation data attributes are not rendered for nested property rules

Using FluentValidation 4.4, the following rules emit the correct unobtrusive validation data attributes on input fields:

RuleFor(e => e.PrimaryContact).NotEmpty();

rendering the following html:

<input class="text-box single-line k-textbox input-validation-error" 
       data-val="true" data-val-required="'Primary Contact' should not be empty." 
       id="PrimaryContact" name="PrimaryContact" type="text" value="">

However, a rule with a nested property does not emit any validation data attributes:

RuleFor(e => e.Company.Name).NotEmpty();

rendering the following html:

 <input class="text-box single-line k-textbox" id="Company_Name" name="Company.Name" type="text" value="">

What am I missing?

Upvotes: 5

Views: 1481

Answers (2)

technicallyjosh
technicallyjosh

Reputation: 3531

That could get a bit sloppy in the case that you need to validate on each property in the child object. I would recommend doing what they have on their documentation here.

[Validator(typeof(ParentObjectValidator))]
public class ParentObject 
{
    public string PrimaryContact {get;set;}
    public Company Company {get;set;}
}

[Validator(typeof(CompanyValidator))] // This one is required!
                                      // Otherwise no data-val-required will be assigned
public class Company
{
    public string Name {get;set;}
}

Set a validator for the child object.

public class CompanyValidator : AbstractValidator<Company> {
    public CompanyValidator() {
      RuleFor(company => company.Name).NotEmpty();
      //etc
    }
}

Then, in your parent object, you can set that validator to the child object like so.

public class ParentObjectValidator : AbstractValidator<ParentObject> {
  public ParentObjectValidator() {
    RuleFor(e => e.PrimaryContact).NotEmpty();
    RuleFor(e => e.Company).SetValidator(new CompanyValidator());
  }
}

This should point you in the right direction!

Upvotes: 4

killer7
killer7

Reputation: 249

I already have the same Problem like "jrummel"!!!

If I define the Validator with SetValidator for my nested ViewModel Object, the MVC EditorFor Method didnt't render any data-val* attributes. And so no client side validation did work...

But every other property(which is not nested an the nested viewModelType) work very well. The inputs have the data-val* attributes. --> WTF?

After I found http://www.paraesthesia.com/archive/2013/04/17/fluentvalidation-and-mvc-from-server-to-client.aspx and I did understood how the validation mechanism did work, i recognized that I'm missing the [Validator(typeof(MyNestedViewModelType))] Attribute on MyNestedViewModelType class.

Hope this helps someone else to save time ;-)

Upvotes: 2

Related Questions