有没有办法使数据注释有条件?我有一个桌子派对,我存储组织和人员。如果我添加一个组织,我不想要现场姓氏,但只有当我添加一个人。
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’)则需要姓氏,否则姓氏可以为空。
编辑
如果我必须把这个验证转移到控制器,那我该怎么做呢?如何从那里触发相同的错误信息?
解决方法
您可以使您的模型继承自
IValidatableObject,然后将自定义逻辑放入验证方法中。您还必须从属性中删除RequredAttribute。您将必须编写一些自定义JavaScript来验证客户端上的此规则,因为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>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。