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

浪尽此生 提交于 2019-12-04 08:24:02
technicallyjosh

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!

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 ;-)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!