条件数据注释

时间:2011-06-23 11:53:13

标签: asp.net-mvc validation data-annotations

有没有办法让数据注释成为条件?我有一个表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')然后需要姓氏,否则姓氏可以为空。

修改
如果我必须将此验证移动到控制器,我该怎么做?如何从那里触发相同的错误消息?

3 个答案:

答案 0 :(得分:32)

您可以使模型继承自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>

答案 1 :(得分:3)

我知道这个主题有一些时间,但是如果您只想使用声明性验证,那么您可以使用这样一个简单的结构(请参阅this reference以获得更多可能性):

[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; }

答案 2 :(得分:0)

在Controller中你可以像这样检查: 之前if(ModelState.IsValid)

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