有条件的数据注解 [英] Conditional data annotation

查看:122
本文介绍了有条件的数据注解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法,使数据注解的条件?我有一个表在这里我同时存储的组织和个人。如果我加入一个组织,我不想的的被需要的领域,但只有当我加入的人。

Is there a way to make a data annotation conditional? I have a table Party where I store both organisations and persons. If I'm adding an organisation I don't want the field surname to be required, but only if I'm adding a person.

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

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

我想把姓所需的数据标注,喜欢的东西的一个条件:结果
如果则需要(party_type =='P')姓,否则姓可以为空。

I'd like a condition for the required data annotation of surname, something like:
if (party_type=='P') then surname is required, else the surname can be empty.

修改结果
如果我有这个验证移动到控制器,我会怎么做呢?我怎么可以触发同样的错误信息从那里?

EDIT
If I have to move this validation to the controller, how would I do it there? How can I trigger the same error message from there?

推荐答案

您可以让你的模型从<一个继承href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.ivalidatableobject.aspx\">IValidatableObject然后把你的自定义逻辑到验证方法。你必须从属性中删除RequredAttribute为好。你将不得不写一些自定义JavaScript来验证客户端上的这条规则的验证方法并没有转化为不显眼的验证框架。注意我改变你的属性为字符串,以避免铸造。

You can make your model inherit from IValidatableObject and then put your custom logic into the Validate method. You'll have to remove the RequredAttribute from the property as well. You will have to write some custom javascript to validate this rule on the client as the Validate method doesn't translate into the unobtrusive validation framework. Note I changed your properties to strings to avoid casting.

另外,如果你从其他的属性验证错误,这会触发第一和prevent Validate方法被运行,所以你只有在基于属性的验证是确定检测这些错误。

Also, if you have other validation errors from attributes, those will fire first and prevent the Validate method from being run so you only detect these errors if the attribute-based validation is ok.

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

在你可以这样做客户端:

On the client you can do something like:

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

这篇关于有条件的数据注解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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