(c#) DataAnnotation:如何处理必须为空的属性?

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

我正在创建一个大力使用 System.ComponentModel.DataAnnotations 和 ExpressiveAnnotations 的模型。

但是我需要一个建议来处理这个案例:

如果属性 1 的值为“ABC”,则属性 2 是必需的(属性 2 是字符串)。这很简单:

ExpressiveAnnotations.Attributes.RequiredIf("attribute1 == 'ABC'")
public string? attribute2 { get; set; }

但是

如果 attribute1 的值与“ABC”不同,则 attribute2 必须为空

如何处理?

我在 MSDN 和其他网站上搜索。不知道可不可以。

c# data-annotations
1个回答
0
投票

您可以创建自定义

ValidationAttribute
,如下面的代码:

using System;
using System.ComponentModel.DataAnnotations;

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class EmptyIfNotABCAttribute : ValidationAttribute
{
    private readonly string _dependentProperty;

    public EmptyIfNotABCAttribute(string dependentProperty)
    {
        _dependentProperty = dependentProperty;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var dependentPropertyValue = validationContext.ObjectInstance.GetType()
            .GetProperty(_dependentProperty)
            .GetValue(validationContext.ObjectInstance, null);

        if (dependentPropertyValue?.ToString() != "ABC" && !string.IsNullOrWhiteSpace(value?.ToString()))
        {
            return new ValidationResult(ErrorMessage);
        }

        return ValidationResult.Success;
    }
}

并在您的模型上实现:

public class YourModel
{
    [RequiredIf("attribute1 == 'ABC'")]
    [EmptyIfNotABC("attribute1")]
    public string attribute2 { get; set; }

    // Other properties
}
© www.soinside.com 2019 - 2024. All rights reserved.