条件数据注释

发布于 2024-11-16 23:14:37 字数 508 浏览 4 评论 0原文

有没有办法使数据注释成为有条件的?我有一个表Party,其中存储组织和个人。如果我要添加一个组织,我不希望需要字段,但前提是我要添加一个人。

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') 则姓氏为必填项,否则姓氏可为空。

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

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

蓝天白云 2024-11-23 23:14:37

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

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.

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>
浮光之海 2024-11-23 23:14:37

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

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

I know this topic has some time, but if you'd like to use only declarative validation for that, you could just use such a simple construction (see this reference for further possibilities):

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

public string party_type { get; set; }

Update:

Since the ExpressiveAnnotations 2.0, there is a breaking change. Now the same thing can be done in a simpler manner:

[RequiredIf("party_type == 'P'")]
public string surname { get; set; }
红ご颜醉 2024-11-23 23:14:37

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

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

In Controller you can check like this:
Before if (ModelState.IsValid)

if (model.party_type == 'p')
{
   this.ModelState.Remove("surname");
}
司马昭之心 2024-11-23 23:14:37

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

I haven't encountered this problem, but I found a possible solution to your problem from data labeling for social media that by the database management system (DBMS) or the application code that interacts with the database. You can also try using a relational database system like MySQL, PostgreSQL, or SQL Server, here are two common approaches to achieve conditional data annotation: Database Triggers, Application-Level Validation. If it doesn't work, we'll try to figure it out.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文