条件数据标注

问题描述 投票:0回答:4

有没有办法使数据注释成为有条件的?我有一张桌子

Party
,用来存放组织和人员。如果我要添加一个组织,我不希望需要字段 surname,但前提是我要添加一个人。

public class Party
{
    [Required(ErrorMessage = "{0} is missing")]
    [DisplayName("Your surname")]
    public object surname { get; set; }

    [DisplayName("Type")]
    public object party_type { get; set; }
    ...
}  

我想要一个姓氏所需数据注释的条件,例如:

if (party_type=='P')
那么姓氏是必需的,否则姓氏可以为空。

编辑
如果我必须将此验证移至控制器,我该怎么做?我怎样才能从那里触发相同的错误消息?

asp.net-mvc validation data-annotations
4个回答
31
投票

您可以让您的模型继承IValidatableObject,然后将您的自定义逻辑放入Validate方法中。您还必须从属性中删除 RequredAttribute。您必须编写一些自定义 JavaScript 来在客户端上验证此规则,因为 Validate 方法不会转换为不显眼的验证框架。请注意,我将您的属性更改为字符串以避免强制转换。

此外,如果您有来自属性的其他验证错误,这些错误将首先触发并阻止 Validate 方法运行,因此只有在基于属性的验证正常时您才会检测到这些错误。

public class Party : IValidatableObject
{
    [DisplayName("Your surname")]
    public string surname { get; set; }

    [DisplayName("Type")]
    public string party_type { get; set; }
    ...

    public IEnumerable<ValidationResult> Validate( ValidationContext context )
    {
         if (party_type == "P" && string.IsNullOrWhitespace(surname))
         {
              yield return new ValidationResult("Surname is required unless the party is for an organization" );
         }
    }
}

在客户端您可以执行以下操作:

 <script type="text/javascript">
 $(function() {
      var validator = $('form').validate();
      validator.rules('add', {
          'surname': {
              required: {
                 depends: function(element) {
                      return $('[name=party_type]').val() == 'P';
                 }
              },
              messages: {
                  required: 'Surname is required unless the party is for an organization.'
              }
           }
      });
 });
 </script>

3
投票

我知道这个主题需要一些时间,但如果您只想使用声明性验证,您可以使用这样一个简单的构造(请参阅此参考了解更多可能性):

[RequiredIf(DependentProperty = "party_type", TargetValue = "P")]
public string surname { get; set; }

public string party_type { get; set; }

更新:

自 ExpressiveAnnotations 2.0 以来,出现了重大变化。现在可以用更简单的方式完成同样的事情:

[RequiredIf("party_type == 'P'")]
public string surname { get; set; }

0
投票

在控制器中你可以这样检查: 在 if (ModelState.IsValid) 之前

if (model.party_type == 'p')
{
   this.ModelState.Remove("surname");
}

0
投票

我没有遇到过这个问题,但我通过数据库管理系统(DBMS)或与数据库交互的应用程序代码从社交媒体的数据标签找到了解决您问题的可能解决方案。您还可以尝试使用 MySQL、PostgreSQL 或 SQL Server 等关系数据库系统,以下是实现条件数据注释的两种常见方法:数据库触发器、应用程序级验证。如果不起作用,我们会尽力解决。

© www.soinside.com 2019 - 2024. All rights reserved.