不显眼的客户端验证数据属性不会呈现为嵌套属性规则 [英] Unobtrusive client validation data attributes are not rendered for nested property rules

查看:72
本文介绍了不显眼的客户端验证数据属性不会呈现为嵌套属性规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用FluentValidation 4.4,下面的规则发出输入字段中输入正确的验证不显眼数据属性:

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

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

呈现以下HTML:

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

呈现以下HTML:

rendering the following html:

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

我是什么失踪?

推荐答案

这可以让在您需要验证在子对象的每个属性的情况下有点马虎。我会建议他们做对他们的<一个什么href=\"http://fluentvalidation.$c$cplex.com/wikipage?title=CreatingAValidator&referringTitle=Documentation&ANCHOR#ReusingValidators\"相对=nofollow>这里文档。

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!

这篇关于不显眼的客户端验证数据属性不会呈现为嵌套属性规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆